js继承的多种方式

150 阅读1分钟

《js高级程序设计》阅读笔记,方便自己以后查阅

1.原型链继承

function SuperType(){

}
SuperType.prototype.sayName = function(){
	return this.name
}

function SubType(){
	this.name = '王一博'
}
SubType.prototype = new SuperType()


var instance = new SubType()
alert(instance.sayName()) // 王一博

缺点:原型上引用类型的实例被所用原型共享,创建实例时,不能向SuperType传参

2.借用构造函数

function SuperType(){
	this.colors = ['red']
}

function SubType(){
	SuperType.call(this)
}

var instance = new SubType()

传递参数

function SuperType(name){
	this.name = name
	this.colors = ['red']
}

function SubType(name){
	SuperType.call(this,name)
}

var instance = new SubType('谦谦')

问题:方法在构造函数中定义,每次创建实例都会新建一个方法,函数无法复用

3.组合继承

function SuperType(name){
	this.name = name
}
SuperType.prototype.sayName = function(){
	return this.name
}

function SubType(name,age){
	SuperType.call(this,age) // 这里调用SuperType
	this.name = name
}
SubType.prototype = new SuperType() // 这里调用 SuperType
SubType.prototype.constructor = SubType

var instance = new SubType('王一博')
alert(instance.sayName()) // 王一博

缺点:会调用两次 SuperType

4.原型式继承

function object(o){
	function F(){}
    F.prototype= o
    return new F()
    
}
var person = {
	name:'aa',
    friends:['yy']
}

var anotherPerson = object(person);
anotherPerson.name = 'Greg'

5.寄生式继承

寄生式继承与寄生构造函数和工厂模式类似

function createAnother(original){
	var clone = object(original)
	clone.sayHi = function(){
    	alert('hi')
    }
    return clone
}

var person = {
	name:'aa',
    friends:['yy']
}
var another = createAnother(person)
another.sayHi() //'hi'

6.寄生组合继承

通过借用构造函数来继承属性,通过原型链的混合形式来继承方法。不必为了制定子类型的原型二调用超类型的构造函数(比如组合继承)

function inheritPrototype(subType,superType){
	var prototype = object(superType.prototype);
    prototype.constructor = subType
    subType.prototype = prototype
}


function SuperType(name){
	this.name = name
}
SuperType.prototype.sayName = function(){
	return this.name
}

function SubType(name,age){
	SuperType.call(this,age) // 这里调用SuperType
	this.name = name
}
inheritPrototype(SubType,SuperType)

SubType.prototype.sayAge = function(){
	console.log('age')
}