Javascript: Calling child function from parent (super?) function.

alotofquestions picture alotofquestions · Sep 26, 2013 · Viewed 15.5k times · Source

Both parent functions are overridden by child. two in the child is calling parent's two. however, i was expecting that at the parent level, the call to one would invoke the child's method. Is there a concept that i am missing?

Thank you in advance!

http://jsfiddle.net/9mbGN/

function parent(){}

parent.prototype.one = function(){
    $('body').append("Parent: one <br/>");
}

parent.prototype.two = function(){
    this.one();
    $('body').append("Parent: two <br/>");
}


function child(){}

child.prototype = new parent();
child.prototype.constructor = child;

child.prototype.one = function(){ //should this function not be called? 
    $('body').append('Child: one <br />');
}

child.prototype.two = function(){
    $('body').append('Child: do some child stuff here and call parent: <br />');
    parent.prototype.two();    
}



var k = new child();
k.two();

Answer

A. Mat&#237;as Quezada picture A. Matías Quezada · Sep 26, 2013

The more optimal way is almost like you are doing it, but you call the parent method over this:

child.prototype.two = function(arg1, arg2) {
  parent.prototype.two.call(this, arg1, arg2);
};

But I recommend you to use a custom function to extend, you can use extend from jsbase

If you are using ECMAScript 5 getters/setters (if not just use the first one) you may prefeer to use the one at this gist

Both can be used the same way based on Dean Edward's idea:

var Animal = extend(Object, {

  constructor: function(name) {
    // Invoke Object's constructor
    this.base();

    this.name = name;

    // Log creation
    console.log('New animal named ' + name);
  },

  // Abstract
  makeSound: function() {
    console.log(this.name + ' is going to make a sound :)');
  },

});

var Dog = Animal.extend({

  constructor: function(name) {
    // Invoke Animals's constructor
    this.base(name);

    // Log creation
    console.log('Dog instanciation');
  },

  bark: function() {
    console.log('WOF!!!');
  },

  makeSound: function() {
    this.base();
    this.bark();
  }
});

var pet = new Dog('buddy');
// New animal named buddy
// Dog instanciation
pet.makeSound();
// buddy is going to make a sound :)
// WOF!!!

In your case it can be:

var parent = extend(Object, {
  one: function() {
    $('body').append("Parent: one <br/>");
  },
  two: function() {
    this.one();
    $('body').append("Parent: two <br/>");
  }
});

var child = parent.extend({
  one: function() {
    $('body').append('Child: one <br />');
  },
  two: function() {
    $('body').append('Child: do some child stuff here and call parent: <br />');
    this.base();
  }
});