JavaScript closure and the this object

后端 未结 2 1608
日久生厌
日久生厌 2021-01-18 18:29

I thought I had a reasonable understanding of the this object in JavaScript. When dealing with objects, callbacks, and both events and handlers, I haven\'t had

相关标签:
2条回答
  • 2021-01-18 19:10

    As soon as you call:

    return func(par);
    

    You're creating a new scope (with its own this) and in this case because you haven't specified an object, this === window usually or undefined in strict mode. The called function does not inherit whatever this was in the calling scope.

    Ways to set a value for this are:

    myobj.func(par);  // this === myobj
    

    or

    func.call(myobj, ...)  // this === myobj
    

    There are also:

    • apply
    • bind
    • arrow functions, where this is set to the same value as the outer execution context (also see MDN:Arrow functions )
    0 讨论(0)
  • 2021-01-18 19:17

    The value of this depends only on whether you call the function as a method or as a function.

    If you call it as a method, this will be the object that the method belongs to:

    obj.myFunction();
    

    If you call it as a function, this will be the window object:

    myFunction();
    

    Note that even if you are in a method that belongs to an object, you still have to call other methods in the object using the method syntax, otherwise they will be called as functions:

    this.myOtherFunction();
    

    If you put a method reference in a variable, you will detach it from the object, and it will be called as a function:

    var f = obj.myFunction;
    f();
    

    The call and apply methods are used to call a function as a method even if it's not a method in the object (or if it's a method in a different object):

    myFunction.call(obj);
    
    0 讨论(0)
提交回复
热议问题