Scope of this in javascript function

前端 未结 3 945
灰色年华
灰色年华 2021-01-20 13:42

If you have the following code:

var global = this;
function A () {
    function B () {
        return this;
    }
    return B();
}
var C = new A();
C === gl         


        
3条回答
  •  长发绾君心
    2021-01-20 14:27

    To accompany Pointy's correct answer:

    The reasoning for this is because you can do whatever you want with functions. You can return function B from function A, and save it as a global variable.

    Or you could append function B as a method to an Object, or a dozen objects. Or you could use it in an AJAX callback, or use it as a callback from a timer.

    Because the engine doesn't know what's going to happen with function B, the language says that this refers to whatever the function is being called on, at the time it's called.

    This adds a lot of dynamism to the language, but it also adds a lot of headache, if you're not sure what "this" is pointing to at any given time.

    Rule of thumb:

    If the function is directly attached as the method of an object, or a function is being called with .call or .apply and being fed a context, like myFunc.call(myObj), then this refers to window.

提交回复
热议问题