Reputation: 455
I've experimented with closures and found unexpected behaviour. Can somebody explain why this code works this way, please?
function foo() {
this.a='hello';
return {
aaa:function() {
return a; // this suprises me, how can be here accessed 'a' ?
}
}
}
o=foo();
alert(o.aaa()); // prints 'hello' ! , I expected undefined
I don't understand, why I always use var that=this
phrase, If it is possible to access function properties from inner functions directly.
jsfiddle https://jsfiddle.net/5co6f707/
Upvotes: 1
Views: 73
Reputation: 105497
When this code is executed:
o=foo();
foo
is executed in global context and so this line:
this.a='hello';
adds a
property to the global object - window
.
When you call your aaa
function like this:
o.aaa()
the variable a
is not defined within the function so it's looked up on up the scope chain and it's found on window:
function() {
return a; // found on window.a
}
and so window.a
is returned.
Upvotes: -1
Reputation: 141829
It displays 'hello'
because you're not in strict mode, so this
is the global window
object instead of undefined, and a
becomes a global variable when you assign a value to this.a
. Since a
is a global variable it is accessible everywhere. You could just alert(a);
at the very end of your script and it would also display 'hello'
: https://jsfiddle.net/5co6f707/1/.
It shouldn't work (and doesn't in strict mode) and it shouldn't be used. If you intend to use foo
as a constructor then you should use the new
keyword when you call it (which would break your code, but in a good way).
Upvotes: 5