实例化对象的传统方法是构造函数:
function Person(name) {
this.name = name;
}
Person.prototype.sayHi = function () {
console.log(`This is ${this.name}`);
}
var person = new Person('Jack');
person.sayHi(); // This is Jack
ES6中引入了Class(类)概念,使用class关键字让对象原型的写法更清晰:
class Person {
constructor (name) {
this.name = name;
}
sayHi() {
console.log(`This is ${this.name}`);
}
}
const person = new Person('Jack');
person.sayHi(); // This is Jack
constructor()方法就是构造方法,this就是实例对象。
Class Person = {
constructor() {}
sayHi(){}
}
// 等同于
Person.prototype = {
constructor() {},
sayHi(){}
};