function SuperType(){
this.property=true}
SuperType.prototype.getSuperValue= function (){
return this.property}
function SubType(){
this.subproperty=false}// 继承 SuperType
SubType.prototype= new SuperType()
SubType.prototype.getSubValue= function (){
return this.subproperty}
let instance = new SubType()
console.log(instance.getSuperValue())//true
复制代码
function SuperType(){
this.colors=["red","blue","green"]}
function SubType(){}// 继承 SuperType
SubType.prototype= new SuperType()
let instance1 = new SubType()
instance1.colors.push("black")
console.log(instance1.colors)//"red,blue,green,black"
let instance2 = new SubType()
console.log(instance2.colors)//"red,blue,green,black"
复制代码
function SuperType(name){
this.name= name
}
function SubType(){// 继承 SuperType 并传参
SuperType.call(this,"Nicholas")// 实例属性
this.age=29}
let instance = new SubType()
console.log(instance.name)//"Nicholas";
console.log(instance.age)//29
复制代码
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
特点:
只继承了父类构造函数的属性,没有继承父类原型的属性。
解决了原型链继承缺点 1、2、3。
可以继承多个构造函数属性(call 多个)。
在子实例中可向父实例传参。
解决了引用值问题
缺点:
只能继承父类构造函数的属性。
无法实现构造函数的复用。
每个新实例都有父类构造函数的副本,臃肿。
三、组合继承(组合原型链继承和借用构造函数继承)(常用)
重点: 结合了两种模式的优点,传参和复用
function SuperType(name){
this.name= name
this.colors=["red","blue","green"]}
SuperType.prototype.sayName= function (){
console.log(this.name)}
function SubType(name, age){// 继承属性
SuperType.call(this, name)//// 第一次调用 SuperType()
this.age= age
}// 继承方法
SubType.prototype= new SuperType()// 第二次调用 SuperType()
SubType.prototype.sayAge= function (){
console.log(this.age)}
let instance1 = new SubType("Nicholas",29)
console.log("instance1=>", instance1)
instance1.colors.push("black")
console.log(instance1.colors)//"red,blue,green,black"
instance1.sayName()//"Nicholas";
instance1.sayAge()//29
let instance2 = new SubType("Greg",27)
console.log(instance2.colors)//"red,blue,green"
instance2.sayName()//"Greg";
instance2.sayAge()//27
复制代码
//核心代码
function object(o){
function F(){}
F.prototype= o
return new F()}
let person ={
name:"Nicholas",
friends:["Shelby","Court","Van"],}
let anotherPerson = object(person)
anotherPerson.name="Greg"
anotherPerson.friends.push("Rob")
let yetAnotherPerson = object(person)
yetAnotherPerson.name="Linda"
yetAnotherPerson.friends.push("Barbie")
console.log(person.friends)//"Shelby,Court,Van,Rob,Barbie"
复制代码
function object(o){
function F(){}
F.prototype= o
return new F()}
function createAnother(original){
let clone = object(original)// 通过调用函数创建一个新对象
clone.sayHi= function (){// 以某种方式增强这个对象
console.log("hi")}
return clone // 返回这个对象
}
let person ={
name:"Nicholas",
friends:["Shelby","Court","Van"],}
let anotherPerson = createAnother(person)
anotherPerson.sayHi()//"hi"//寄生式继承同样适合主要关注对象,而不在乎类型和构造函数的场景。object()函数不是寄生式继承所必需的,任何返回新对象的函数都可以在这里使用。
// 注意 通过寄生式继承给对象添加函数会导致函数难以重用,与构造函数模式类似。
复制代码