我了解到JavaScript(ES6)的最新版本现在支持创建类。我也知道,在ES5和之前的JS版本中创建和使用对象的通常方式是创建对象原型。那么,使用类与原型相比有什么区别,何时使用这两种方法呢?:
类方法:
class Car {
constructor(brand) {
this.carname = brand;
}
printStatement() {
return "I have a " + this.carname + ".";
}
}
mycar = new Car("Toyota");
document.getElementById("demo").innerHTML = mycar.printStatement(); // outputs "I have a Toyota."
原型法:
function Person(firstName, lastName, age, eyecolor) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.eyeColor = eyecolor;
}
//adding a new method to the prototype:
Person.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};
var john = new Person("John", "Doe", 43, "Blue");
console.log(john.fullName); // outputs "John Doe"