Javascript:从父( super ?)函数调用子函数。

标签 javascript inheritance prototype-programming

两个父函数都被子函数覆盖。 child 中的两个叫 parent 的两个。但是,我期望在父级别,对一个的调用将调用子方法。有没有我想念的概念?

提前致谢!

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();

最佳答案

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

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

但是我建议你使用自定义函数来扩展,你可以使用 extend from jsbase

如果您正在使用 ECMAScript 5 getters/setters(如果不只是使用第一个),您可能更喜欢使用 this gist 中的那个。

根据 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!!!

在您的情况下,它可以是:

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();
  }
});

关于Javascript:从父( super ?)函数调用子函数。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19019287/

相关文章:

javascript - 如何使用 ElementRef 关闭外部点击 Angular 4 上的下拉菜单

javascript - 如何将自定义 HTML map 标记添加到诺基亚 HERE map ?

javascript - Deno:为 Node.js 内置提供 Polyfill

python - 如何使用继承在python中定义父对象?

java - 在静态测试文件中调用非静态方法

javascript - javascript 是否在原型(prototype)之外存储数据类型信息?

javascript - 何时以及为何使用“调用申请”?

javascript - IE 7 崩溃并直接关闭,没有任何消息

css - Shadow DOM 插槽内的继承

Javascript 文字与函数 oop