Reputation: 15
I have several business objects (with different types) that implement functions for a common object, which is assigned to a property of each business object. It is possible to call the functions declared on business objects from the common object?
Hereafter some similar code:
var Percent= function(){
this.input= null;
...
this.getValuesRange= function(){
return [min,max];
}
...
}
var Speed= function(){
this.input= null;
...
this.getValuesRange= function(){
return [min,max];
}
...
}
var Input= function(){
this.inputRange= function(){
//here I need to call owner's getValuesRange function
}
}
var input= new Input();
var mySpeed= new Speed();
var rocketSpeed= new Speed();
...
mySpeed.input= input;
rocketSpeed.input= input;
...
facade.enter(mySpeed);
facade.enter(rocketSpeed);
...
Upvotes: 0
Views: 373
Reputation: 1264
This is possible with some workarounds. Here an example:
var c = 0;
var Speed= function(){
var mc = c++;
var _input = null;
var _inputRange = null;
this.getInput= function() {
var self = this;
_input.inputRange = function() {
_inputRange.call(self);
}
return _input;
}
this.setInput= function(input) {
_input = input;
_inputRange = input.inputRange;
}
this.getValuesRange= function(){
console.log("Speed", mc);
}
}
var Input= function(){
this.inputRange= function(){
this.getValuesRange()
}
}
var input= new Input();
var mySpeed= new Speed();
var rocketSpeed= new Speed();
mySpeed.setInput(input);
rocketSpeed.setInput(input);
mySpeed.getInput().inputRange(); // Speed 0
rocketSpeed.getInput().inputRange(); // Speed 1
There are many possible pitfalls with this solution. It's here only tho give an idea.
Upvotes: 0
Reputation: 1074138
For inputRange
on Input
to access getValuesRange
, it has to have access to an instance of Speed
. Your code has to provide it that instance, there's no built-in "what object references this object via a property" operation in JavaScript. (If there were, it would have to allow for the fact multiple objects can reference the same object, as in your example — both Speed
instances reference the same Input
instance.)
Upvotes: 1