When we store a method in a variable and then call it, Why does the context object change to the global window object?

StackOverflow https://stackoverflow.com/questions/23215488

Frage

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?

War es hilfreich?

Lösung

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:

  1. If the function code is strict code, set the ThisBinding to thisArg.
  2. 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.

Andere Tipps

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’.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top