Access parent function from JavaScript object

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 get "undefined not a function" because obviously parentFunction () is not in scope, but I'm not sure what is the best way to make it accessible?

+4
source share
3 answers

As thisin Childwill refer to the Childobject not Parent, so save a link thisof Parentvariable that can be used later 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();
Run codeHide result
+1
source
var Parent = function() {
 this.Child = {
    childFunction: function() {
      this.parentFunction();
    }
  };
  this.parentFunction = function() {

  }
};

Now inside this.Child childFunctionthis will refer to the Child object, not the Parent.

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

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

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

      }
    };

Parent.parentFunction().

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

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

      }
    };
0

The problem is that thisyours childFunctionrefers to the current object, which is Child.

A common solution would be to access the parent using a variable accessible through closure . For instance:

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

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

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

As an alternative, a more cumbersome approach would be to use bind to “bind” the function context childFunctionto the current this(which is the parent):

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

See MDN

0
source

All Articles