Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 重新定义原型方法_Javascript_Prototype - Fatal编程技术网

Javascript 重新定义原型方法

Javascript 重新定义原型方法,javascript,prototype,Javascript,Prototype,我试图在JavaScript中模拟“类”语法。重新定义对象时,如何从对象的原型调用函数?在这个例子中,我试图扩展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.pro

我试图在JavaScript中模拟“类”语法。重新定义对象时,如何从对象的原型调用函数?在这个例子中,我试图扩展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)

您可以直接访问动物原型上的方法:

Bear.prototype.sound = function() { 
 Animal.prototype.sound.call(this); 
 console.log("growl!"); 
};

!那又怎么样?This:Object.setPrototypeOf(熊、动物、原型)?无论是
Object.setPrototypeOf(Bear.prototype,Animal.prototype)
(我建议避免)还是
Bear.prototype=Object.create(Animal.prototype)
。请给出一个原因,为什么要创建超过setPrototypeOf?