How can I access baz() from inside the bar() function in the following code?
var obj = {
baz : function(){ alert("Hi!"); },
foo: {
bar: function(){
baz();
}
}
}
How can I access baz() from inside the bar() function in the following code?
var obj = {
baz : function(){ alert("Hi!"); },
foo: {
bar: function(){
baz();
}
}
}
JavaScript doesn't have kind of a built-in parent reference because an object can be referenced by multiple 'parents' in what we call a many-to-one relationship.
As others have said, in this simplified case, simply calling obj.baz() will work.
In a more complicated case, you would have to manually build the object and track parenthood:
// Create the root object
var rootObject = {baz: function() {console.log('rootBaz');}}
// And the basic child
var childObject = {foo: function() {console.log('childFoo');}}
// Configure the parent
childObject.parent = rootObject;
// Add our call.
childObject.baz = function() {this.parent.baz()};
// Invoke and test
childObject.baz();
Which can be slightly simplified:
var rootObject = {
baz: function() {console.log('rootBaz');}
};
var childObject = {
foo: function() {console.log('childFoo');},
baz: function() {this.parent.baz()}
};
childObject.parent = rootObject;
childObject.baz();
Updated per Sujet's comment
In addition, if you need to make sure that baz has the correct value for this you can use either call or apply.
baz: function() {this.parent.baz.call(this.parent)}
If your code doesn't require this then I would recommend a straight function call per my original answer.
You need to reference via object.property notation.
In your example you would get baz via:
obj.baz()
Some great resources for this: