Javascript:一个对象如何存储对另一个对象的引用's方法,并将其称为“s”;“远程”;

Javascript: How can an object store a reference to another object's method, and call it "remotely"?

本文关键字:一个对象 方法 远程 何存储 存储 引用 Javascript      更新时间:2023-09-26

所以,我得到了两个对象,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的It定义。

因此,如果您存储a.met = b.met,然后在函数this === a 中调用a.met()

在JavaScript花园阅读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() {}
        });
    }
}

最简单的解决方案:

a.met = function() { b.met(); };

或使用.bind(参见MDC),语义相同:

a.met = b.met.bind(b);

如果你的函数很多,并且它们有参数,你也可以做这个

function B() {
    this.x = "I am b";
}
function A() {
    this.x = "I am A";
}
B.prototype.met = function() {
    alert(this.x);
}
A.prototype.met = B.prototype.met;

您可以使用B.prototype中所需的功能更新A.prototype。