Reputation: 45124
Below example is taken from jqfundamentals,
var person = {
firstName : 'Boaz',
lastName : 'Sender',
greet : function() {
log( 'Hi, ' + this.firstName );
}
};
var sayIt = person.greet; // store the method in a variable
sayIt(); // logs 'Hi, undefined' -- uh-oh
As explanation,
When we store the .greet() method in a variable sayIt and then call sayIt(), the context object changes to the global window object, not the person object. Since the window object doesn't have a property firstName, we get undefined when we try to access it.
My problem is
When we store the .greet() method in a variable sayIt and then call sayIt() Why does the context object change to the global window object?
Upvotes: 1
Views: 45
Reputation: 365
The context object change to global window because you do not have any context and by default, the "this" refers to window object when there is no context assigned.
You can see an explanation in this link: http://www.laurencegellert.com/2012/03/javascript-the-good-parts-review/
The behavior the ‘new’ keyword is convoluted and non-obvious. When an object/function is created, adding the new keyword changes the meaning of ‘this’. When ‘new’ is added, ‘this’ refers to the object, which makes sense. However in the next code block, where ‘new’ is omitted, ‘this’ refers to the global Window object! The code example shows how the global object can be polluted. Watch out for ‘this’.
Upvotes: 1
Reputation: 160923
It's the spec, See the ecma-262/5.1/#sec-10.4.3
The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisArg, and a caller provided argumentsList:
- If the function code is strict code, set the ThisBinding to thisArg.
- Else if thisArg is null or undefined, set the ThisBinding to the global object.
.......
So when in strict mode, this
will refer to undefined
, otherwise it will refer to the global object.
Upvotes: 2