我是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
}
})()
当我看到猫()对象在调试窗口,它显示我没有财产“突袭”,靴子也没有。我在这里做什么不起作用?
我会认为,因为我将函数添加到对象的原型,它将被添加到原型链,因此被继承。
非常感谢您的时间。
这不是你如何使用原型! 'this .__ proto__ = new Animal()'是错误的!使用'Cat.prototype = Object.create(Animal.prototype)'和'Animal.apply(this)'来正确地创建一个继承。 – somethinghere
现在我更加困惑。你能举个例子吗? – SemperCallide
正在工作!这似乎是一个很好的尝试,但是误导了:) – somethinghere