When you pass myFunction2
as an argument to something, it loses the reference to the object it belongs to. this
now refers to the function itself, and not someScopeScopedObject
, hence your problem :)
This is also why some libraries take an object context for methods, ie. jasmine's spyOn(someScopeScopedObject, "myFunction2")
, to keep the scoping correct.
An example work-around (like the one used by jasmine) could look like this:
var someScopeScopedObject = {
myFunction1: function () {
console.log('foo');
},
myFunction2: function () {
this.myFunction1();
},
init: function (context, callbackName) {
context[callbackName]();
}
}
This would allow you to do the following:
someScopeScopedObject.init(someScopeScopedObject, "myFunction2");
This is not the prettiest. Alternatively, you can bind the object to the function (so the scope stays the same). This assumes your original code in someScopeScopedObject
:
someScopeScopedObject.init(someScopeScopedObject.myFunction2.bind(someScopeScopedObject));
Neither of these are pretty, and, really, that's because it is weird to externally feed a function belonging to an object as a callback to that object.
The best solution might be:
someScopeScopedObject.init(function() {
someScopeScopedObject.myFunction2();
});