Function context (“this”) in nested functions

后端 未结 5 1267
名媛妹妹
名媛妹妹 2021-02-09 17:26

When you invoke a top-level function in Javascript, the this keyword inside the function refers to the default object (window if in a browser). My understanding is that

5条回答
  •  青春惊慌失措
    2021-02-09 18:21

    When you define func in the global scope, it actually is assigned as a property of the window object. That is, the window object holds all globally scoped variables. (*) Therefore, func and window.func represent the same thing. innerFunc is defined inside a function scope and is not available outside of that scope. Therefore, window.innerFunc is (still) undefined.

    However, the this context is determined by how you call the function. When you call a method like obj.method(), the this context is set to obj. On the other hand, you can also call the method on its own:

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

    In this case, you're not calling a function on an object and thus the this context is set to the default. The default however is the global scope and as stated above, this is represented by window.

    You can always override the this context by using Function.prototype.call() or Function.prototype.apply() which take a this context as first argument. For example:

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

    (*) Note that this only applies to JavaScript running inside a browser. In other environments, this may differ. For example, in Node.js the GLOBAL variable holds the global scope.

提交回复
热议问题