Javascript: How can an object store a reference to another method of the object and call it "remotely"?

So, I have two objects: a and b. Now I want to pass one of the b methods to the object that should store it. Let me call this method b.met:

b.met=function(){
    alert(this.txt);
}

Now, I want to call b.met from a. The following code does not work, since a.met is a clone of b.met inside the scope:

a.met=b.met;
a.met(); //Executes in the 'a' scope!

The only way I found is to store the method name in a string and use it in the eval expression:

a.toCall='b.met';
eval(a.toCall+'();');

Since everyone says you should avoid using eval ... what other options exist?


EDIT - see comments: So, I changed my code:

a:{
    processes:[],
    spawnProcess:function(type,id,closeFn){
    var closeFn=closeFn || 'function(){}';
    this.processes.push({type:type,id:id,closeFn:closeFn});
}

at

a:{
    processes:[],
    spawnProcess:function(type,id,closeFn){
    var closeFn=function(){closeFn()} || 'function(){}';
    this.processes.push({type:type,id:id,closeFn:function(){closeFn()}});
}

When I execute the following code, I get a too big recursion error:

a.spawnProcess('','',b.met);
a.processes[0].closeFn();
+3
source share
3

. - . this .

, a.met = b.met, a.met() this === a

JavaScript this

, , .

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

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

.bind ES5. - _.bind $.proxy

Edit

a.spawnProcess('','',b.met);

to

a.spawnProcess('','', function() {
    b.met();
});

,

a: {
    processes: [],
    spawnProcess: function(type, id, closeFn) {
        this.processes.push({
            type: type,
            id: id,
            closeFn: closeFn || function() {}
        });
    }
}
+7

:

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

.bind (. MDC), :

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

, ,

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;

A.prototype , B.prototype.

0

All Articles