构造对象的2中方式
1. 构造函数+prototype
let peopleList = []
const ageList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
function createPeople(age) {
const object = Object.create(createPeople.peoplePrototype)
object.age = age
return object
}
createPeople.peoplePrototype = {
//将原型放在函数上
getDoubleAge() {
return this.age * 2
},
constructor: createPeople, // 方便使用原型找到构造函数
}
for (let i = 0; i <= 11; i++) {
peopleList[i] = createPeople(ageList[i])
}
使用 new 操作符优化
let peopleList = []
const ageList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
function People(age) {
this.age = age
}
People.prototype.getDoubleAge = function () {
return this.age * 2
}
for (let i = 0; i <= 11; i++) {
peopleList[i] = new People(ageList[i])
}
new 自动做了四件事
- 自动创建空对象
- 自动为空对象关联原型,原型地址指定为 X.prototype
- 自动将空对象作为 this 关键字运行构造函数
- 自动 return this
2. ES6 class(语法糖)
let peopleList = []
const ageList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
class People {
age = 0 // 定义属性 默认值:0
constructor(age) {
this.age = age
}
getDoubleAge() {
return this.age * 2
}
}
for (let i = 0; i <= 11; i++) {
peopleList[i] = new People(ageList[i])
}