<!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>
近期评论