比如下面的程序:function classA(){
    this.x = 0;
    this.show = function(){
        alert(this.x);
    }
    this.show();
}
new classA();
这里应该如何理解show()函数中的this呢?我感觉可以有两种解释
1.show()是一个闭包,所以show()中的this是直接使用了外部classA()函数的this。此时,两个this是同一个变量。
2.show()函数被调用时会隐含传递一个调用它的对象的引用,也就是this,所以show()中的this只是和外部的this的值相同,担不是同一个变量。(Java中就是这种)应该是那种解释呢?

解决方案 »

  1.   

    this指调用函数的对象默认global(window)对象调用window.x = 'window';
    function f(){
        console.log(this.x);
    }f(); // window({x: 1, f: f}).f(); // 1({x: 2, f: f}).f(); // 2this.show()
    因为是this调用,show中的this也就是这个this了。
      

  2.   

    你这里所有的this都没有别的意思,指的就是ClassA类的对象
      

  3.   

    this就是当前应用的对象,谁调用谁就是this,不一定是ClassA,如果用了call或apply的话就是对用的对象了
      

  4.   


    你是说应该是第二种解释?那如何证明第一种解释是错的呢?this.show()中使用了外部的this也可以说的通呀
      

  5.   

    只是传递一个引用            x = 1;
                function classA(){
        this.x = 0;
        this.show = function(){
            alert(this.x);
        }
        this._show = function(){
         this.show.call(window);
        }
        this._show();
    }
    var a = new classA();
      

  6.   

    的确是传递一个引用,谢谢了x = 1;
                function classA(){
                    this.x = 0;
                    this.show = function(){
                        alert(this.x);
                    }
                    
                    this.show.call(window);
    this.show.call(this);
                }
                var a = new classA();