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

后端 未结 4 1093
抹茶落季
抹茶落季 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条回答
  •  悲哀的现实
    2020-12-08 22:44

    The scope of all functions is window.

    To circumvent that, you can do this:

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

提交回复
热议问题