混入模式(Mixin)
混入模式的目的是为了函数复用,丰富一些需要使用这些复用函数的类
var Car = function(settings) {
this.modal = settings.modal || 'no';
}
var Mixin = function() {};
Mixin.prototype = {
driveForword: function() {
console.log('--向前')
},
driveBackward: function() {
console.log('--向后')
},
driveSideways: function() {
console.log('靠边')
}
};
function augment(receivingClass, givingClass) {
if (arguments[2]) {
for (let i = 2; i<arguments.length;i++) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
}
}
// 混入模式目的是函数复用,丰富一些需要这些复用函数的类
augment(Car, Mixin, 'driveForword', 'driveBackward');
var carObj = new Car({
modal: '自动挡'
});
carObj.driveForword();
carObj.driveBackward();
修饰模式
修饰模式主要是对构造函数的实例进行修改
function MacBook() {
this.cost = function() {
return 997;
}
this.screenSize = function() {
return 11.6
}
}
// 装饰器1 主要修改的是类的实例 不改变原类的构造函数
function memory( macbook ) {
var v = macbook.cost();
macbook.cost = function() {
return v + 1000;
};
}
// 装饰器2
function engraving( macbook ){
var v = macbook.cost();
macbook.cost = function(){
return v + 200;
};
}
var mb = new MacBook();
memory( mb );
console.log( mb.cost());
engraving( mb );
console.log(mb.cost());