[removed] why “this” inside the private function refers to the global scope?

后端 未结 4 1095
抹茶落季
抹茶落季 2020-12-08 22:08

Consider the following code:

function A() {}    

A.prototype.go = function() {
    console.log(this); //A { go=function()}

    var f = function() {
                


        
4条回答
  •  旧时难觅i
    2020-12-08 22:56

    The reason why is you are invoking f as a function and not a method. When invoked as a function this is set to window during the execution of the target

    // Method invocation.  Invoking a member (go) of an object (a).  Hence 
    // inside "go" this === a
    a.go();
    
    // Function invocation. Invoking a function directly and not as a member
    // of an object.  Hence inside "f" this === window
    f(); 
    
    // Function invocation. 
    var example = a.go;
    example();
    

提交回复
热议问题