我正在尝试编写一个从父类扩展的 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();
但问题是,如何调用父对象上的方法。
有什么想法吗?
最佳答案
使用原型(prototype)。它们允许您访问父类(super class)的方法,但无需对其进行实例化。
然后,从子类,你可以做 SuperClass.prototype.instanceMethod.call(this)
,这在大多数典型的 OO 语言中基本上是 super
,但是 JS不能帮助您弄清楚父类(super class)是什么。所以你必须自己跟踪它。
// 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 继承可能很困惑,但有一些方法可以提供帮助。
仅举几例。
关于javascript - 如何在 Javascript 的子类中重载父类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13961032/