(function(){
console.info("寄生组合式继承")
// 寄生组合式继承
function object(o){
function F(){}
F.prototype = o;
return new F()
}
function inheritPrototype(subType, superType){
var prototype = Object(superType.prototype)
prototype.constructor = subType; // 增强对象 bug: 这里实际上是把superType.prototype.constructor改成了subType
subType.prototype = prototype; // 指定对象
}
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"]
}
SuperType.prototype.sayName = function(){
alert(this.name)
}
var instance1 = new SuperType()
console.log(instance1 instanceof Object)
console.log(instance1 instanceof SuperType)
console.log(instance1 instanceof SubType)
console.log(Object.prototype.isPrototypeOf(instance1))
console.log(SuperType.prototype.isPrototypeOf(instance1))
console.log(SubType.prototype.isPrototypeOf(instance1))
function SubType(name, age){
SuperType.call(this, name)
this.age = age;
}
inheritPrototype(SubType, SuperType)
SubType.prototype.sayAge = function(){
alert(this.age)
}
console.log(instance1 instanceof Object)
console.log(instance1 instanceof SuperType)
console.log(instance1 instanceof SubType)
console.log(Object.prototype.isPrototypeOf(instance1))
console.log(SuperType.prototype.isPrototypeOf(instance1))
console.log(SubType.prototype.isPrototypeOf(instance1))
/**
* 优点:只调用了一次SuperType构造函数,并且因此避免了在SubType.prototype上创建不必要的、多余的属性。
* 缺点:事实上在调用inheritPrototype方法时,会把superType.prototype.constructor改成subType,
* 使得对一个超类的实例使用instanceof和SubType.prototype.isPrototypeOf的结果在调用inheritPrototype前后会发生变化。
* 为了避免这个问题可以使用:
* function object(o){
* function F(){}
* F.prototype = o;
* return new F()
* }
* 即object(superType.prototype)来代替上文的Object(superType.prototype)。
* 或者直接使用Object.create(superType.prototype),即创建一个原型为等于superType.prototype的实例,
* 但值得注意的是Object.create只有IE 9+ Firefox 4+ Safari 5+ Opera 12+ 和 Chrome才支持。
*/
}())