Scope of this in javascript function

前端 未结 3 872
灰色年华
灰色年华 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:26

    this has nothing to do with scope, it's not a variable. It's a keyword that evaluates to the currently executing function's object context. The function's object context is determined by how you call it. It doesn't matter where or how the function is defined.

    When you call a function like fn() then it is not in object context and the language wrongly attempts to work around it when it should just throw an error at the mere sight of this. This is somewhat fixed in strict mode where it would evaluate to undefined.

    When you call a function as a property of some object I.E. obj.fn() then obj is bound to this for that call.

    Since it would be clunky having to attach a function to some object just to get the right object context for the call, all functions inherit a .call method that allows you to specify the object context explicitly:

    return B.call(this); 
    

提交回复
热议问题