function Human (age) {
this.type = "big"
this.family = ["爸爸","妈妈"]
this.age = age
this.str = function() {return this.age+ "-" + this.type}
}
Human.prototype.proStr = function () {
return this.type + "+" + this.age
}
一、原型链继承
function Man () {}
Man.prototype = new Human(24)
var tom = new Man()
tom.family.push("姐姐")
console.log(tom.family) //["爸爸", "妈妈", "姐姐"]
var bob = new Man()
console.log(bob.family) //["爸爸", "妈妈", "姐姐"]
console.log(bob.str()) //24 - big
console.log(tom.str == bob.str) //true 共用原型中的str 方法
console.log(tom.proStr()) //big+24
缺点
* 实例无法传参
* 原型中的引用数据类型被共用
二、构造函数继承
function Woman(age) {
Human.call(this,age)
}
var lily = new Woman(20)
lily.family.push("哥哥")
console.log(lily.family,lily.age) //["爸爸", "妈妈", "哥哥"]
var mary = new Woman(23)
console.log(mary.family,mary.age) //["爸爸", "妈妈"]
console.log(mary.str()) //23 - big
console.log(lily.str == mary.str) //false 各自拥有一个str方法,赋值得到
console.log(mary.proStr()) //TypeError: mary.proStr is not a function
缺点
* 无法共用原型中的公有方法和属性
* 无法获取原型中prototype里的属性和方法
三、组合继承
function Child(age) {
Human.call(this,age)
}
Child.prototype = new Human()
var piter = new Child(4)
piter.family.push("哥哥")
console.log(piter.family,piter.age) //["爸爸", "妈妈", "哥哥"]
var susy = new Child(6)
console.log(susy.family,susy.age) //["爸爸", "妈妈"]
console.log(susy.str()) //6-big
console.log(susy.str == piter.str) //false 各自拥有一个str方法,赋值得到
console.log(susy.proStr()) //big+6 可以使用原型的prototype里的属性和方法
console.log(susy.proStr == piter.proStr) //true
缺点
* 多次使用原型函数
四、原型式继承(原型链继承的另一种方式)
function getObj(o) {
function Test () {}
Test.prototype = o
return new Test()
}
var person = {
name: "xiaoming",
family: ["爸爸","妈妈"]
}
var obj1 = getObj(person)
obj1.family.push("大舅")
var obj2 = getObj(person)
console.log(obj2.family) //["爸爸","妈妈","大舅"]
缺点
* 同原型链继承
五、寄生继承(原型式+工厂模式)
function getData(o) {
function Fun () {}
Fun.prototype = o
return new Fun()
}
function createData (o) {
var obj = getData(o)
obj.arr = [1,2,3,4]
return obj
}
var child = {
name: "xiaoming",
family: ["爸爸","妈妈"]
}
var data1 = createData(child)
data1.family.push("大叔")
var data2 = createData(child)
console.log(data2.family) //["爸爸","妈妈", "大叔"]
console.log(data1.arr == data2.arr) //false
缺点
* 引用数据类型共用
六、寄生组合继承
function getperData (o) {
function Fun () {}
Fun.prototype = o
return new Fun() //返回实例
}
function createYouth(Human,Youth) { //寄生函数
var obj = getperData(Human.prototype)
obj.constructor = Youth //改变构造函数指向
Youth.prototype = obj
}
function Youth(age) {
Human.call(this,age) //将原型中的引用数据私有化
}
createYouth(Human,Youth)
var yada = new Youth(26)
yada.family.push("大姑")
console.log(yada.str())
console.log(yada.proStr())
var hawa = new Youth(25)
console.log(hawa.family) //["爸爸", "妈妈"]
console.log(hawa.str == yada.str) //false
console.log(yada.proStr == hawa.proStr) //true
console.log(yada.constructor) //原始构造函数指向Human Youth.prototype = Human.prototype 修改后指向Youth