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?

Amir Shahbabaie
  • 1,352
  • 2
  • 14
  • 33

1 Answers1

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();
Ele
  • 33,468
  • 7
  • 37
  • 75