我是 Javascript 的新手,这是一个关于继承的基本问题。
在我正在查看的网站中,向对象的原型(prototype)添加新方法看起来非常简单。这是他们展示的方法:
function Gadget(name, color) {
this.name = name;
this.color = color;
}
Gadget.prototype.getInfo = function() {
return 'Rating: ' + this.rating + ', price: ' + this.price;
};
但是尝试复制相同的内容时,我收到错误:
(function() {
window.onload = function() {
document.getElementById("main").innerHTML = getMessage();
}
function Animal(){
this.speak = function(){
return "I am a " + this.species + ", hear me " + this.sound + "!";
}
}
function Cat(){
this.__proto__ = new Animal();
this.species = "cat";
this.sound = "meow";
}
function getMessage(){
var cat = new Cat();
Cat.prototype.pounce = function() { return "Pounce!"}; //Adding prototype function here
var Boots = {};
Boots.__proto__ = new Cat();
return cat.speak() + '<br>' + Boots.pounce(); //Returning message that Boots.pounce() doesn't exist
}
})()
当我在调试窗口中查看 Cat() 对象时,它显示它没有属性“pounce”,Boots 也没有。我在这里做什么不起作用?
我认为,既然我将函数添加到对象的原型(prototype)中,它就会被添加到原型(prototype)链中,从而被继承。
非常感谢您抽出时间。
最佳答案
__proto__
的行为从未标准化,除了 legacy feature 之外。 .
如果您使用Object.create
,您会玩得更开心。方法。它将原型(prototype)作为第一个参数并返回使用该原型(prototype)的对象。
如果使用 Object.create
重写,您的代码可能看起来更像这样。
function Animal() {
}
// you don't need to this, but it shows the prototype chain explicitly
Animal.prototype = Object.create(Object.prototype);
Animal.prototype.speak = function() {
return "I am a " + this.species + ", hear me " + this.sound + "!";
};
function Cat(){
this.species = 'cat';
this.sound = 'meow';
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.pounce = function() {
return "Pounce";
};
function getMessage() {
var cat = new Cat();
// you could dynamically add methods to the prototype, but the
// code will be faster if you declare the properties on the
// prototype, as early as possible
var Boots = new Cat();
return cat.speak() + '<br>' + Boots.pounce();
}
关于javascript - 通过 .prototype 添加到对象的方法没有被继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32782503/