Reputation: 697
I've gotten to the point where I am trying to fill out my javascript knowledge with some of the more advaned concepts.
I think I a pretty much understand how scope works. Where objects inherit from a prototype and then global scope, while functions offer a more traditional block scope within themselves.
What I am have trouble understanding is this:
function a(){
console.log(this.z);
}
a.z = 12;
a(); //returns undefined :(
I was expecting to echo out 12, but of course, it doesn't. Where exactly is z being stored? what does "this" refer to in the example?
Upvotes: 4
Views: 284
Reputation: 239473
When you call a function, JavaScript will set the current context (this
) as the object on which it is called. If the function is not attached to any object, by default global object (window
object in browsers) will be used *.
So, in this case, this
refers to the global object, not a
. In the global object, z
hasn't been defined yet. That is why it returns undefined
.
To get the value 12, you need to access it like this
function a() {
console.log(a.z); // Use `a` itself, instead of `this`.
}
a.z = 12;
a();
* In strict mode, this
will be set to undefined
, if the function is called without any explicit object reference.
Upvotes: 2