‘mixin模式’

mixin模式 –感觉类似于cpp里面的抽象出来的超类, 子类对象可以很轻松的集成超类中的属性和方法,优点:
增加了函数复用,减少代码量。

代码实现

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
38
39
40
41
42
43
44
45
46
47
48
49
50
<!DOCTYPE html>
<html>
<head>
<title>Mixin模式</title>
</head>
<body>
<script>
var Car = function(settings) {
this.model = settings.model || 'no model provided',
this.color = settings.color || 'no color provided'
}
var Mixin = () {}
Mixin.prototype = {
driveForward: () {
console.log('drive forword');
},
driveBackward: () {
console.log('drive backwords')
}
};
function argument(receivingClass, givingClass) {
if(arguments[2]) {
for(var i = 2, len = arguments.length; i < len; i++) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
} else {
for(var key in givingClass) {
if(!Object.hasOwnProperty(receivingClass.prototype, key)) {
receivingClass.prototype[key] = givingClass.prototype[key];
}
}
}
}
//只添加特定的方法到Car里面
argument(Car, Mixin, 'driveForward', 'driveBackward');
var myCar = new Car({
model:'BWM',
color:'red'
});
myCar.driveForward();
myCar.driveBackward();
</script>
</body>
</html>