所以,我得到了两个对象,a 和 b。现在,我想将 b 的方法之一传递给应该存储它的 a 对象。我们将该方法称为 b.met:
b.met=function(){
alert(this.txt);
}
现在,我想从 a 调用 b.met。以下代码不起作用,因为 a.met 是 a 范围内 b.met 的克隆:
a.met=b.met;
a.met(); //Executes in the 'a' scope!
到目前为止,我发现的唯一方法是将方法的名称保存在字符串中并在 eval 语句中使用它:
a.toCall='b.met';
eval(a.toCall+'();');
既然每个人都说你应该避免使用 eval... 还有什么其他的可能性吗?
编辑 - 见评论:所以我改变了我的代码:
a:{
processes:[],
spawnProcess:function(type,id,closeFn){
var closeFn=closeFn || 'function(){}';
this.processes.push({type:type,id:id,closeFn:closeFn});
}
到:
a:{
processes:[],
spawnProcess:function(type,id,closeFn){
var closeFn=function(){closeFn()} || 'function(){}';
this.processes.push({type:type,id:id,closeFn:function(){closeFn()}});
}
当执行下面的代码时,我得到了太多的递归错误:
a.spawnProcess('','',b.met);
a.processes[0].closeFn();
最佳答案
您存储对函数的引用。函数只是一个函数。它根据调用上下文获取 this
的定义。
因此,如果您存储 a.met = b.met
,然后在该函数内调用 a.met()
this === a
阅读at the JavaScript garden about this
您要做的是存储函数和调用它的上下文。
这可以通过以下方式完成
a.met = function() {
b.met();
}
或
a.met = b.met.bind(b);
.bind
需要 ES5。推荐的跨浏览器替代品包括 _.bind
和 $.proxy
编辑
你需要改变
a.spawnProcess('','',b.met);
到
a.spawnProcess('','', function() {
b.met();
});
你可能也想要这个
a: {
processes: [],
spawnProcess: function(type, id, closeFn) {
this.processes.push({
type: type,
id: id,
closeFn: closeFn || function() {}
});
}
}
关于Javascript:对象如何存储对另一个对象方法的引用,并将其称为 "remotely"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6089641/