[英]Setting supertypes for objects in Javascript
我正在学习 freecodecamp.org 上的某个课程,但我发现了一个我无法理解的案例,尽管有解释。
我从这个代码开始:
function Cat(name) {
this.name = name;
}
Cat.prototype = {
constructor: Cat,
eat: function() {
console.log("nom nom nom");
}
};
function Bear(name) {
this.name = name;
}
Bear.prototype = {
constructor: Bear,
eat: function() {
console.log("nom nom nom");
}
};
function Animal() { }
Animal.prototype = {
constructor: Animal,
};
本课是关于在为不同的对象设置原型时避免重复。 在这种情况下,我们看到Cat
和Bear
的原型都有相同的方法eat
。 所以建议的解决方案是设置一个包含该方法的超类型。
function Cat(name) {
this.name = name;
}
Cat.prototype = {
constructor: Cat,
};
function Bear(name) {
this.name = name;
}
Bear.prototype = {
constructor: Bear,
};
function Animal() { }
Animal.prototype = {
constructor: Animal,
eat: function() {
console.log("nom nom nom");
}
};
这一切都很棒,但是……它在哪里定义的, Animal
是Bear
和Cat
的超类型? 这段代码似乎有效,这让我很困惑。
考虑下面的代码:
function Animal(name) {
this.name = name;
}
Animal.prototype = {
slogan() {
return 'be a good one';
}
}
function Dog(name) {
this.name = name;
}
这里有两个构造函数。 为了将 Animal 原型分配给 Dog 我们这样做:
Dog.prototype = Object.create(Animal.prototype);
对 Object.Create() 方法的解释:
Object.create() 方法用于创建具有指定原型对象和属性的新对象。 Object.create() 方法返回一个具有指定原型对象和属性的新对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.