在玩ES6之后,我真的开始喜欢新的语法和功能了,但我确实对类有疑问.
新的ES6类是旧原型模式的语法糖吗?或者幕后还有更多的事情发生在这里?即:
class Thing {
//... classy stuff
doStuff(){}
}
Run Code Online (Sandbox Code Playgroud)
vs:
var Thing = function() {
// ... setup stuff
};
Thing.prototype.doStuff = function() {}; // etc
Run Code Online (Sandbox Code Playgroud) 我知道最新版本的 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."
Run Code Online (Sandbox Code Playgroud)
原型方法:
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 + " " …Run Code Online (Sandbox Code Playgroud)