The method obj2.method1, in the code below, is called from another object.
How do I bind the “this context” so that I can refer to obj1 from obj2?
var singleton = {
obj1 : {
a : 5
},
obj2 : {
method1 : function(){
this.obj1.a; //undefined
}
}
}
I tried using underscore _.bindAll() – something along these lines – but failed …
var singleton = {
obj1 : {
a : 5
},
obj2 : {
method1 : function(){
this.obj1.a; //undefined
}
},
init : function(){
_.bind(this, obj2.method1)
}
}
singleton.init();
Thanks 🙂
You need to reassign
singleton.obj2.method2()with the results of_.bind():// in .init():
this.obj2.method1 = _.bind(this.obj2.method1, this)
To have
singleton.init()have a properthiswhen called, you need to specify it explicitly:singleton.init.call(singleton)
Full demonstration here. But remember, the
Singletonpattern is bad, m’kay?