实际JavaScript中并没有类
实例化
继承
多态
多继承
混入
显式混入
function mixin(sourceObj, targetObj) {
for (let key in sourceObj){
if (!(key in targetObj)){
targetObj[key]=sourceObj[key];
}
}
return targetObj;
}
let Vehicle={
engines:1,
ignition:function () {
console.log("turning on my engine");
},
drive:function () {
this.ignition();
console.log("steeing and moving forward");
}
};
let Car=mixin(Vehicle,{
wheels:4,
drive:function () {
Vehicle.drive.call(this);
console.log("Rolling on all "+this.wheels,+" wheels!");
}
});
寄生继承
function Vehicle() {
this.engines=1;
}
Vehicle.prototype.ignition=function () {
console.log("turning on my engine");
};
Vehicle.prototype.drive=function () {
this.ignition();
console.log('Steering and moving forward');
};
function Car() {
let car=new Vehicle();
car.wheels=4;
let vehDrive=car.drive;
car.drive=function () {
vehDrive.call(this);
console.log("Rolling on all "+this.wheels+" wheels");
};
return car;
}
let myCar=new Car();
myCar.drive();
隐式混入
let Something={
cool:function () {
this.greeting="hello world";
this.count=this.count?this.count+1:1;
}
};
Something.cool();
console.log(Something.greeting,Something.count);
let Another={
cool:function () {
Something.cool.call(this);
}
};
Another.cool();
console.log(Another.greeting,Another.count);