JavaScript 面向对象

1
2
3
4
function Person (name, age) {
this.name = name
this.age = age
}

当我们 const person = new Person("lgy", 30) 的时候,到底发生了什么呢?

1
2
3
4
5
6
7
8
9
10
11
12
/* 伪码 */
function Person (name, age) {
const result = {} // 创建一个新对象
this = result //
result.__proto__ = Person.prototype // 使 新创建 的result继承自Person [^1]

// 执行Person的函数体
this.name = name
this.age = age // this => {name: name, age: age, __proto__: Person.prototype}

return this // 把 this 指向的对象返回
}