(抱歉,又是一个关于JavaScript中this
的问题。)
我有以下代码,并且想知道结尾处的' this '表示什么—— Window还是Bird?
var Bird = (function () {
Bird.name = 'Bird';
function Bird(name) {
this.name = name;
}
Bird.prototype.move = function (feet) {
return alert(this.name + (" flew" + feet + "ft."));
};
return Bird;
}).call(this);
call
时,第一个参数是你正在执行的上下文/范围,它不会作为函数的参数传递。要正确测试你所建议的内容,可以尝试(function(){ console.log(this); }).call(this);
。如果你想看到参数,请尝试(function(arg){ console.log(this, arg); }).call(this, this);
。这两个测试都显示'this'是window
。 - Mattcall(this, "okay")
,而“okay”是定义Bird的匿名函数的第一个参数。使用“this,this”,它就是窗口。 - CodeClown42