【发布时间】:2020-01-15 15:43:57
【问题描述】:
我了解最新版本的 JavaScript (ES6) 现在支持创建类。我也明白在 ES5 和早期版本的 JS 中创建和使用对象的常用方法是创建对象原型。那么,使用类和下面这样的原型有什么区别,什么时候使用这两种方法呢?:
类方法:
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return "I have a " + this.carname + ".";
}
}
mycar = new Car("Toyota");
document.getElementById("demo").innerHTML = mycar.present(); // outputs "I have a Toyota."
原型方法:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
//adding a new method to the prototype:
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
var john = new Person("John", "Doe", 43, "Blue");
console.log(john.name); // outputs "John Doe"
【问题讨论】:
-
ES6(或 ECMAScript 2015)不是 ECMAScript 的最新版本。
-
区别只是语法
-
比副本中的任何一个更好的答案:stackoverflow.com/a/49643668/816620.
标签: javascript ecmascript-6 javascript-objects