Let's suppose I have an object like this in javascript:
obj = {
prop1 : 0,
prop2 : 1,
func1 : function (){
var x = {
func_Inner : function(){
//ATTEMPTING TO CALL FUNC2 ON obj WON'T WORK
this.func2()
//NEITHER THIS
this.func2().bind(obj);
}
}
x.f()
this.func2()
},
func2 : function (){
console.log(this)
console.log(this.prop1,this.prop2)
}
}
I'd like to call func2 from inside func_Inner , how could I?
asked Apr 9, 2018 at 14:40
Amir Shahbabaie
1,4222 gold badges16 silver badges35 bronze badges
1 Answer 1
The problem is the context of the function func_Inner which is not the obj's context.
An alternative is binding the context this to the function func_Inner
var obj = {
prop1 : 0,
prop2 : 1,
func1 : function (){
var x = {
func_Inner : function(){
//ATTEMPTING TO CALL FUNC2 ON obj WON'T WORK
this.func2()
//NEITHER THIS
//this.func2().bind(obj);
}
}
// Here's is bound to the current context.
x.func_Inner.bind(this)();
},
func2 : function (){
//console.log(this)
console.log(this.prop1,this.prop2)
}
}
obj.func1();
answered Apr 9, 2018 at 14:47
Ele
33.8k7 gold badges43 silver badges80 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Amir Shahbabaie
Got it. That's embarrassing for me to do the bind thinggy in wrong place
lang-js
x.f()bex.func_Inner()? I don't see anffunction defined anywhere.obj.func2().obj.func2()maybe?!