Javascript this points to Window object

一曲冷凌霜 提交于 2019-11-27 23:08:06

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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!