对象的创建模式
Object 构造函数模式
- 套路: 先创建空 Object 对象, 再动态添加属性/方法
- 适用场景: 起始时不确定对象内部数据
- 问题: 语句太多
- 示例:
1
2
3
4
5var obj = {}
obj.name = 'Tom'
obj.setName = function (name) {
this.name = name
}
对象字面量模式
- 套路: 使用{}创建对象, 同时指定属性/方法
- 适用场景: 起始时对象内部数据是确定的
- 问题: 如果创建多个对象, 有重复代码
- 示例:
1
2
3
4
5
6var obj = {
name: 'Tom',
setName: function (name) {
this.name = name
},
}
工厂模式
- 套路: 通过工厂函数动态创建对象并返回
- 适用场景: 需要创建多个对象
- 问题: 对象没有一个具体的类型, 都是 Object 类型
- 示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15function createPerson(name, age) {
//返回一个对象的函数===>工厂函数
var obj = {
name: name,
age: age,
setName: function (name) {
this.name = name
},
}
return obj
}
// 创建2个人,都是是Object类型
var p1 = createPerson('Tom', 12)
var p2 = createPerson('Bob', 13)
自定义构造函数模式
- 套路: 自定义构造函数, 通过 new 创建对象
- 适用场景: 需要创建多个类型确定的对象
- 问题: 每个对象都有相同的数据, 浪费内存
- 示例:
1
2
3
4
5
6
7
8function Person(name, age) {
this.name = name
this.age = age
this.setName = function (name) {
this.name = name
}
}
new Person('tom', 12)
构造函数+原型的组合模式
- 套路: 自定义构造函数, 属性在函数中初始化, 方法添加到原型上
- 适用场景: 需要创建多个类型确定的对象
1
2
3
4
5
6
7
8function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.setName = function (name) {
this.name = name
}
new Person('tom', 12)
继承模式
原型链继承
- 套路1: 定义父类型构造函数
- 套路2: 给父类型的原型添加方法
- 套路3: 定义子类型的构造函数
- 套路4: 创建父类型的对象赋值给子类型的原型
- 套路5: 将子类型原型的构造属性设置为子类型
- 套路6: 给子类型原型添加方法
- 套路7: 创建子类型的对象: 可以调用父类型的方法
- 关键:子类型的原型为父类型的一个实例对象
1 | function Parent() {} // 创建父类 |
借用构造函数
- 套路1:定义父类型构造函数
- 套路2:定义子类型构造函数
- 套路3:在子类型构造函数中调用父类型构造
- 关键:在子类型构造函数中通用 call()调用父类型构造函数
- 示例:
1
2
3
4
5
6
7
8function Parent(xxx) {
this.xxx = xxx
}
Parent.prototype.test = function () {}
function Child(xxx, yyy) {
Parent.call(this, xxx) //借用构造函数 this.Parent(xxx)
}
var child = new Child('a', 'b') //child.xxx为'a', 但child没有test()
原型链+借用构造函数的组合继承
利用原型链实现对父类型对象的方法继承
利用 super()借用父类型构建函数初始化相同属性
1
2
3
4
5
6
7
8
9
10function Parent(xxx) {
this.xxx = xxx
}
Parent.prototype.test = function () {}
function Child(xxx, yyy) {
Parent.call(this, xxx) //借用构造函数 this.Parent(xxx)
}
Child.prototype = new Parent() //得到test()
Child.prototype.constructor = Child //修正constructor属性
var child = new Child() //child.xxx为'a', 也有test()new 一个对象背后做了些什么?
- 创建一个空对象
- 给对象设置
__proto__
, 值为构造函数对象的 prototype 属性值1
this.__proto__ = Fn.prototype
- 执行构造函数体(给对象添加属性/方法)