Javascript:从父(超级?)函数调用子函数.

alo*_*ons 9 javascript inheritance prototype-programming

两个父函数都被子进程覆盖.孩子中有两个叫父母的两个.但是,我期望在父级别,对一个人的调用会调用孩子的方法.有一个我缺少的概念吗?

先感谢您!

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();
Run Code Online (Sandbox Code Playgroud)

A. *_*ada 4

更优化的方法几乎就像你正在做的那样,但是你调用父方法this

child.prototype.two = function(arg1, arg2) {
  parent.prototype.two.call(this, arg1, arg2);
};
Run Code Online (Sandbox Code Playgroud)

但我建议你使用自定义函数来扩展,你可以extendjsbase使用

如果您使用 ECMAScript 5 getters/setters(如果不只使用第一个),您可能更喜欢使用这个要点

根据 Dean Edward 的想法,两者可以以相同的方式使用:

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!!!
Run Code Online (Sandbox Code Playgroud)

在你的情况下它可以是:

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();
  }
});
Run Code Online (Sandbox Code Playgroud)