2

How can I access baz() from inside the bar() function in the following code?

var obj = {
    baz : function(){ alert("Hi!"); },
    foo: {
        bar: function(){ 
            baz(); 
        }
    }
}
2
  • 4
    obj.baz will work in this simplified case Commented Oct 18, 2015 at 12:43
  • That's not a "parent" in the OOP sense. Commented Oct 18, 2015 at 13:59

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @HorsSujet. Done.
1

Just use the object reference:

var obj = {
    baz : function(){ alert("Hi!"); },
    foo: {
        bar: function(){ 
            obj.baz(); 
        }
    }
}

Comments

0

You need to reference via object.property notation.

In your example you would get baz via:

obj.baz()

Some great resources for this:

Comments

Your Answer

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.