我正在尝试在 JavaScript 中模拟“类”语法。重新定义对象时如何从对象的原型(prototype)中调用该函数?在示例中,我尝试扩展 Bear 对象的声音功能。
function Animal(name) {
this.name = name;
}
Animal.prototype.sound = function() { console.log("I'm " + this.name); }
function Bear(name) {
Animal.call(this, name)
}
Bear.prototype = new Animal();
Bear.prototype.sound = function() { this.prototype.sound(); console.log("growl!"); }
const cal = new Bear("Callisto")
cal.sound() // Should be: I'm Callisto growl!
console.log(cal)
最佳答案
您可以直接访问 Animals 原型(prototype)上的方法:
Bear.prototype.sound = function() {
Animal.prototype.sound.call(this);
console.log("growl!");
};
关于javascript - 重新定义原型(prototype)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54379822/