4

How would I do the following:

var Parent = function() {
 this.Child = {
    childFunction: function() {
      this.parentFunction();
    }
  };
  this.parentFunction = function() {

  }
};
var parentObj = new Parent();
parentObj.Child.childFunction();

At the moment I'm getting "undefined is not a function" because obviously parentFunction() isn't in scope, but I'm not sure what the best way to make it accessible is?

3 Answers 3

1

As this in Child will refer to Child object not Parent thus Store the reference of this of Parent in a variable which can be used later in childFunction.

var Parent = function() {
  var _self = this; //Store the reference
  this.Child = {
    childFunction: function() {
      _self.parentFunction(); //Use here
    }
  };
  this.parentFunction = function() {
    alert('In parentFunction');
  }
};
var parentObj = new Parent();
parentObj.Child.childFunction();

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

Comments

0
var Parent = function() {
 this.Child = {
    childFunction: function() {
      this.parentFunction();
    }
  };
  this.parentFunction = function() {

  }
};

Now inside this.Child childFunction this will refer to Child object and not the Parent.

So you must use self/that to refer to the parent.

 var Parent = function() {
     var that = this;
     this.Child = {

        childFunction: function() {
          that.parentFunction();
        }
      };
      this.parentFunction = function() {

      }
    };

You can just use Parent.parentFunction() as well.

 var Parent = function() {
     this.Child = {

        childFunction: function() {
          Parent.parentFunction();
        }
      };
      this.parentFunction = function() {

      }
    };

Comments

0

The problem is that this in your childFunction refers to the current object which is Child.

The common solution would be to access the parent using a variable that is available through a closure. For example:

var Parent = function() {
    var _this = this;

    this.Child = {
       childFunction: function() {
          _this.parentFunction();
       }
     };

    this.parentFunction = function() {
        // ...
    }
};

Alternatively, a more cumbersome approach would be to use bind to 'tie' the function context of the childFunction to the current this (which is the parent):

childFunction: function() {
    this.parentFunction();
}.bind(this);

See MDN

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.