比如下面的程序: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中就是这种)应该是那种解释呢?
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中就是这种)应该是那种解释呢?
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了。
你是说应该是第二种解释?那如何证明第一种解释是错的呢?this.show()中使用了外部的this也可以说的通呀
function classA(){
this.x = 0;
this.show = function(){
alert(this.x);
}
this._show = function(){
this.show.call(window);
}
this._show();
}
var a = new classA();
function classA(){
this.x = 0;
this.show = function(){
alert(this.x);
}
this.show.call(window);
this.show.call(this);
}
var a = new classA();