So, I got two objects, a and b. Now, I want to pass one of b’s methods to the a object, wich should store it. Let’s call that method b.met:
b.met=function(){
alert(this.txt);
}
Now, I want to call b.met from a. The following code doesn’t work, since a.met is a clone of b.met inside the scope of a:
a.met=b.met;
a.met(); //Executes in the 'a' scope!
The only way I found, by now, is to save the method’s name in a string and use it in an eval statement:
a.toCall='b.met';
eval(a.toCall+'();');
Since everyone says you should avoid using eval… what other possibilities are there?
EDIT – see in comments: So I changed my code from:
a:{
processes:[],
spawnProcess:function(type,id,closeFn){
var closeFn=closeFn || 'function(){}';
this.processes.push({type:type,id:id,closeFn:closeFn});
}
to:
a:{
processes:[],
spawnProcess:function(type,id,closeFn){
var closeFn=function(){closeFn()} || 'function(){}';
this.processes.push({type:type,id:id,closeFn:function(){closeFn()}});
}
When executing the following code, I get a too much recursion error:
a.spawnProcess('','',b.met);
a.processes[0].closeFn();
Your storing a reference to a function. A function is just a function. It get’s it’s definition for
thisbased on the calling context.So if you store
a.met = b.metand then calla.met()inside that functionthis === aRead up at the JavaScript garden about
thisWhat you want to do is store the function and the context to call it in.
This can be done either as
or
a.met = b.met.bind(b);.bindrequires ES5. Recommended cross browser alternatives include_.bindand$.proxyEdit
You need to change
a.spawnProcess('','',b.met);to
You probably also want this instead