When you declare a local variable inside the function, you add it to the VariableEnvironment of the functions (which essentially has no difference from the outer LexicalEnvironment, but the ECMA distinguishes them). The function has a reference to the LexicalEnvironment of the scope in which it was declared (in our case, the global object or window). When you try to reference the variable from inside the function, the engine first searches for it the the native VariableEnvironment of the function, and then, if not found, in the outer LexicalEnvironment. In your case, you try to reference a variable from outside of the function, so the engine searches for it in the scope of global object at the very start.
So, to accomplish your task, you should either declare the variable in the outer scrope, and then assign it inside the function, or you should add a new property to the object and then reference it:
var foo = {
test: 'Hello world',
speak: function()
{
console.log(this.test);
}
};