In the code below:
var x = {
y: function() {
console.log(this === global); // false
function z() {
console.log(this === global); // true
};
z();
}
};
x.y();
When you call y
, you are providing the execution context of x. As such this
is the x object.
Why is the execution context of z
the global object (or window object in a browser)?
It seems like it would be impossible to create a different execution context for z
in the way it is defined. i.e. this.z()
, global.z()
, x.z()
, y.z()
all error with the message that there is no z
function in that execution context.
For this reason, is it true to say that functions defined in the form function name() {}
are ALWAYS defined in the global object's execution context? AND that unless call/bind/apply are used to invoke the function, execution is ALSO ALWAYS in the global object context?
Question: why does a function in this form function name() ...
get defined in the global context and not the context of the object it is written in?
The above is in response to this article: http://www.digital-web.com/articles/scope_in_javascript/
"What if we just call a normal, everyday function...
<script type="text/javascript">
function test_this() {
return this;
}
var i_wonder_what_this_is = test_this();
</script>
In this case, we weren’t provided a context by new, nor were we given a context in the form of an object to piggyback off of. Here, this defaults to reference the most global thing it can: for web pages, this is the window object."