0

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
4
  • 1
    Should x.f() be x.func_Inner()? I don't see an f function defined anywhere. Commented Apr 9, 2018 at 14:42
  • In this specific case you could simply call obj.func2(). Commented Apr 9, 2018 at 14:43
  • Have a look at javascript - How does the "this" keyword work? - Stack Overflow Commented Apr 9, 2018 at 14:44
  • obj.func2() maybe?! Commented Apr 9, 2018 at 15:23

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Got it. That's embarrassing for me to do the bind thinggy in wrong place

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.