# 装饰器模式
- 描述:希望在不改变原对象的基础上,通过对其拓展功能和属性来实现更复杂的逻辑
- 好处:并没有破坏和修改原来的构造函数,以后有新的功能增加,只需要单独的声明一个函数即可,减少了对构造函数的修改和介入
- 例子:
// 一般写法,将方法和属性写在原型链上
function Car() {
this.price = 10;
}
Car.prototype = {
addHeatSeat: function() {
this.hasHeatSeat = true;
this.price += 2;
},
addAutoMirror: function() {
this.hasAutoMirror = true;
this.price += 0.8;
},
};
var car1 = new Car();
console.log(car1.price);
car1.addHeatSeat();
car1.addAutoMirror();
console.log(car1.price);
// 装饰器写法,减少对原函数的修改。单独写一个函数,将实例传到原型里面进行装饰,对这个实例进行属性和方法的增加
function Car() {
this.price = 10;
}
function carWithHeatSeat(carClass) {
carClass.hasHeatSeat = true;
carClass.price += 2;
}
function carWithAutoMirror(carClass) {
carClass.hasAutoMirror = true;
carClass.price += 0.8;
}
var car2 = new Car();
console.log(car2.price);
carWithHeatSeat(car2);
carWithAutoMirror(car2);
console.log(car2.price);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37