【发布时间】:2020-01-15 15:39:47
【问题描述】:
所以当我了解更多关于 JS 中的Prototypal Inheritance 时,我在MDN 文章中阅读了以下内容(阅读此链接上方的行)
请注意,当我们调用构造函数时,我们每次都在定义 greeting(),这并不理想。为了避免这种情况,我们可以在原型上定义函数,我们稍后会看到。
推荐的想法是在函数上添加properties,在prototype上添加methods(阅读here)
Person.prototype.farewell = function() {
alert(this.name.first + ' has left the building. Bye for now!');
};
我在很多地方都是这样阅读的
对象创建速度更快,因为
farewell不是为每个对象创建创建的。这是因为它被创建一次并附加到prototype,并且所有对象链接 到prototype。在
prototypal chain上查找方法,因此每个对象都链接到prototype上的相同方法。
现在是 ES6 类。我有以下代码
class Person {
constructor(first, last, age, gender, interests) {
this.name = {
first: first,
last: last
};
this.age = age;
this.gender = gender;
this.interests = interests;
}
greeting () {
console.log("Hi! I am", this.name.first);
}
farewell () {
console.log(this.name.first, "has left the building. Bye for now!");
}
}
似乎使用这种方法greeting 和farewell 将被再次创建(遵循与函数相同的逻辑,因为class 是一种语法糖)
所以,我把班级改成
class Person {
constructor(first, last, age, gender, interests) {
this.name = {
first: first,
last: last
};
this.age = age;
this.gender = gender;
this.interests = interests;
}
}
Person.prototype.greeting = function () {
console.log("Hi! I am", this.name.first);
}
Person.prototype.farewell = function () {
console.log(this.name.first, "has left the building. Bye for now!");
}
问题
1.后一种方式(在ES6 class中添加方法prototype)是推荐的方式吗?
2、class和传统new Function创建新对象的逻辑是否一致? Copy 与 Method on Prototype?
如果还有什么我遗漏的,请告诉我
谢谢
更新
在几个答案之后,我重试了我的例子并确认了答案。我的代码看起来像
class Phone {
constructor(company, name, color, price) {
this.company = company;
this.name = name;
this.color = color;
this.price = price;
}
print() {
console.log(this.company, this.name, this.color, this.price);
}
}
class Apple extends Phone {
constructor(name, color, price) {
super("Apple", name, color, price);
this.companyWork = "ClosedSource";
}
}
let iPhone11 = new Apple("iPhone11", "black", 900);
iPhone11.print()
【问题讨论】:
-
这两个代码 sn-ps 做同样的事情。类方法是类原型对象的属性。
-
谢谢@Paulpro,你能引用参考吗?
-
"似乎用这种方法会再次创建问候和告别" - 呃,不。它们没有放在
constructor中,它们位于class语法中,这会将它们放在类的原型对象中。
标签: javascript class inheritance ecmascript-6 prototype