Reputation: 787
I have this code:
function Selector(){
this.name = 'Selector';
this.select = function(fName){
return this[fName]
}
this.funcOne = function(arg){
console.log(arg + this.name)
}
}
var mySelector = new Selector();
mySelector.select('funcOne')('Hello');
When I call funcOne
with this implementation, the context within funcOne
is the function itself, not the Selector
instance. How can I maintain the context of the instance by calling funcOne in this way?
Edit: I'm using Extendscript, which is an ES3 environment, so I can't use bind() or arrow functions. What I need exactly is to be able to pass the parameters of the selected function separately, since the idea is, on one hand, to be able to select different functions with a number of different arguments, and on the other, to be able to chain calls using parentheses syntax:
function Selector(){
this.name = 'Selector';
this.select = function(fName){
return this[fName]
}
this.funcOne = function(arg){
console.log(arg + this.name)
return this.select
}
this.funcTwo = function(arg1, arg2)
{
console.log(arg1 + arg2 + this.name)
return this.select
}
}
var mySelector = new Selector();
mySelector.select('funcOne')('Hello');
mySelector.select('funcTwo')('Hello ', 'my ')('funcOne')('Hello again ');
So using a pointer to the instance does not help either, since the problem with the context still remains:
function Selector(){
var self = this
this.name = 'Selector';
this.select = function(fName){
return this[fName]
}
this.funcOne = function(arg){
var s = self; // undefined
}
}
Upvotes: 2
Views: 417