Paul
Paul

Reputation: 3

What is the best way to access to "this" inside a sub object in javascript class?

This doesn't work because f.bar.bar() in undefined.

var myFunction = function(foo){
    this.foo = foo;
    this.bar = {        
        bar: function(){                
            return this.foo;
        }
   }    
}
var f = new myFunction('foo');
alert(f.bar.bar());

Upvotes: 0

Views: 33

Answers (1)

somethinghere
somethinghere

Reputation: 17340

You can always declare a variable in the parent scope:

var myFunction = function(foo){
    var func = this;
    this.foo = foo;
    this.bar = {        
        bar: function(){                
            return func.foo;
        }
   }    
}
var f = new myFunction('foo');
alert(f.bar.bar());

Upvotes: 2

Related Questions