Javascript this points to Window object - Stack Overflow

I have the following code. I expected to see "archive" object on my firebug console, but I se

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);

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);
Share Improve this question asked Apr 27, 2010 at 8:11 MoonMoon 22.6k72 gold badges198 silver badges276 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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.

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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744965566a4603658.html

相关推荐

  • Javascript this points to Window object - Stack Overflow

    I have the following code. I expected to see "archive" object on my firebug console, but I se

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信