I am looking for the best way to deal with this case of double context switching.
function myObject() {
this.data = {};
}
myObject.prototype.each = function(func) {
if (func) {
for (var key in this.data) {
func(key);
}
}
}
function myObject2() {
this.data = {};
}
myObject2.prototype.someFunc = function(o) {
// o = myObject
o.each.call(this, function(key) {
this.data[key] *= o.data[key];
});
}
In myObject2.someFunc I use call to change the context so I can access myObject2's data. However, because of this, in myObject's each method, this now refers to myObject2. If I don't use call then I cannot access the data in myObject2.
I thought about using apply and then passing the original object as an argument and passing it back but I am looking for a more elegant solution that does not require me to change the original defition of myObject.each.
Thanks!
func.call(this, key);otherwisethisin the callback from "someFunc" won't work.