Javascript - 调用父函数和扩展方法

时间:2017-04-23 10:13:02

标签: javascript oop

这可能是一个愚蠢的问题,但在Javascript(ES5首选)和#34;扩展"一个类功能类似于我如何扩展父母' PHP中的函数?

基本上,我有System的这个类层次结构 - > Weapon - > Dual我希望Dual使用System.setState()中的代码,然后再做更多的事情。

注意我的层次结构使用了预先ES6语法。

function System(system){
    this.setState = function(){
        //do stuff
    }
}

function Weapon(system){
    System.call(this, system);
}
Weapon.prototype = Object.create(System.prototype);


function Dual(system){
    Weapon.call(this, system);

    this.setState = function(){ // this is the problem
        System.prototype.setState(); // error - not defined
        //Weapon.protoype.setState() doesnt work either
        //do more stuff
    }
}
Dual.prototype = Object.create(Weapon.prototype);

2 个答案:

答案 0 :(得分:3)

由于setStateSystem实例属性,因此System.proptotype上存在,因此您无法做到使用System.prototype.setState.call调用它。如果你想在这种情况下调用它,只需从System创建一个对象,如此

function Dual(system){
    Weapon.call(this, system);
    var parent = new System(system);

    this.setState = function() {
        parent.setState(); // done
    }
}
每个单独对象

实例属性重复(他们不共享)。然而,原型属性将在子代之间共享(它们不会在子类上重复)。要使所有System子类共享setState函数,请将其添加到System原型

function System (arg) { ... }
System.prototype.setState = function () {...}

现在在您的子课程中,您可以

function Dual(system){
    Weapon.call(this, system);

    this.setState = function() {
        System.prototype.setState.call(this); // done
    }
}

答案 1 :(得分:1)

首先,您应该在原型上设置实例方法:

System.prototype.setState = function() {
    // your stuff
}

这将提高性能并允许您在不构建System实例的情况下继承该方法。

然后,您只需要在正确的对象(System的实例)上调用setState的{​​{1}}版本,而不是在Dual上调用它}:

System.prototype