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.