Function context ("this") in nested functions

When you call a top-level function in Javascript, this keyword inside the function refers to the default object (window, if in a browser). I understand that this is a special case of calling a function as a method, because by default it is called in a window (as explained in John Rezig’s book "Secrets of JavaScript Ninja", page 49). Indeed, both calls in the following code are identical.

function func() {
  return this;
}

// invoke as a top-level function
console.log(func() === window); // true

// invoke as a method of window
console.log(window.func() === window); // true

So far so good ... Now here is the part I don’t understand:

When a function is nested in another function and called without specifying the object to be called, this keyword inside the function also refers to the window. But the internal function cannot be called in the window (see code below).

function outerFunc() {
  function innerFunc() {
    return this;
  }

  // invoke without window.* - OK
  console.log(innerFunc() === window); // true

  // invoke on window
  //window.innerFunc(); - error (window has no such method)
  console.log(window.innerFunc) // undefined
}

outerFunc();

, , ... , , , ?

EDIT

.

  • , "" . , .

  • ( ) , / , , .

  • , , "" , ( ).

  • bind . , "", , . , , , . , , , bind , , apply. - , , , , apply.

"", :

myFunction();

, :

  • () - -

  • -

  • ( ) - -

, , . !

+5
5

, functionName(). , (window). (IIRC, undefined, ).

, . .

, reference.to.object.function(), object .

, , new apply, call bind.

+1

JavaScript, , . - window.

, JavaScript , . window.innerFunc.

+1

, this . , :

  • "" , this :

    someObject.prop( whatever );
    

    , ​​.

  • call() apply() , this , .

  • bind(), this bind().

  • new, this .

  • this , undefined ( , ES5).

"" , , , , , , , , , .

0

, ​​, :

var obj = {
   f: function() {
       return this;
   }
}

var f = obj.f;

console.log(obj.f()) // obj
console.log(f()) // window/default obj

, . obj.f() this=obj, f() this=window. JavaScript this.

0

func , window. window . (*) func window.func . innerFunc . , window.innerFunc ( ) undefined.

this , . obj.method(), this obj. , :

var f = obj.func;
f(); // in this call: this === window

, , , this . , , window.

this, Function.prototype.call() Function.prototype.apply(), this. :

var f = obj.func;
f.call(obj); // in this call: this == obj

(*) , JavaScript, . . , Node.js GLOBAL .

0

All Articles