1

我正在尝试编写一个从父类扩展的javascript类,重载一个方法并稍微更改它。

例如,它检查一些变量,如果它们被设置为真,那么它在父节点上执行相同的方法,否则它执行一些不同的代码。

这就是我想出的:

function Dad(name)    
{
    this.yell = function()
    {
        console.log( 'GRRRRRRR ' + name);
    }
}

function Kid(name, age)    
{
    var parent = new Dad(name);


    parent.yell = function()
    {
        if (age < 15)
            console.log( 'BAAAAA ' + name );
        else
            parent.yell(); //This is the problem line, how to call this method on
                           //parent object
    }
    return parent;
}

var k = new Kid('bob', 13);
k.yell();

但是问题是,如何调用父对象的方法。

有任何想法吗?

4

1 回答 1

2

使用原型。它们允许您访问超类的方法,但无需实例化它。

然后,从子类,你可以做SuperClass.prototype.instanceMethod.call(this),基本上super是大多数典型的OO语言,但是JS并不能帮助你弄清楚超类是什么。所以你必须自己跟踪它。

// Superclass
function Dad() {};
Dad.prototype.yell = function() {
    console.log("Do your homework!");
}

// Subclass
function Kid(age) {
    // calls the constructor of the superclass.
    // in this case, the Dad() constructor does nothing, so it's not required here.
    Dad.call(this);

    // save constructor argument into this instance.
    this.age = age;
};

// Inheritance happens here, prototype is an instance of superclass
Kid.prototype = new Dad();

// Make sure the constructor is properly assigned.
Kid.prototype.constructor = Kid;

// Override an instance method.
Kid.prototype.yell = function() {
    if (this.age < 18) {
        console.log('Waaaaa, I hate homework');
    } else {
        // calls the yell method of the superclass
        Dad.prototype.yell.call(this);
    }
}

// make a kid.
var k = new Kid(13);
k.yell(); // 'Waaaaa, I hate homework' 

// make an old kid.
var k = new Kid(30);
k.yell(); // 'Do your homework!' 

JS 中的 OO 继承可能很混乱,但有一些东西可以提供帮助。

仅举几例。

于 2012-12-19T21:03:15.983 回答