Javascript这指向Window对象 [英] Javascript this points to Window object
问题描述
我有以下代码。我希望在我的firebug控制台上看到archive对象,但是我看到了Window对象。这是正常的吗?
I have the following code. I expected to see "archive" object on my firebug console, but I see Window object. Is it normal?
var archive = function(){}
archive.prototype.action = {
test: function(callback){
callback();
},
test2: function(){
console.log(this);
}
}
var oArchive = new archive();
oArchive.action.test(oArchive.action.test2);
推荐答案
oArchive.action.test2
获取对 callback
然后指向的函数的引用,但是然后使用 callback()调用该函数
,这意味着它不作为方法调用,因此此
是全局对象。关键点是这个
没有绑定到函数:它取决于函数的调用方式。
oArchive.action.test2
gets you a reference to a function that callback
then points to, but that function is then called using callback()
, which means it is not called as a method and hence this
is the global object. The key point is that this
is not bound to a function: it's determined by how the function is called.
在这种情况下,您可以通过使用回调函数的调用$ c $显式地使
此
指向操作对象(但不是归档对象) c>或 apply
方法:
In this case you could explicitly make this
point to the action object (but not the archive object) by using the callback function's call
or apply
method:
test: function(callback) {
callback.call(this);
},
要获得此
成为归档对象,你需要传递归档对象:
To get it this
to be the archive object instead, you'll need to pass the archive object in:
var archive = function(){}
archive.prototype.action = {
test: function(callback, archive){
callback.call(archive);
},
test2: function(){
console.log(this);
}
}
var oArchive = new archive();
oArchive.action.test(oArchive.action.test2, oArchive);
这篇关于Javascript这指向Window对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!