继承
盗用构造函数
盗用构造函数有时称作“对象伪装”或者“经典继承”,是在子构造函数里面调用父构造函数。因为毕竟函数就是在特定的上下文中执行代码的简单对象,所以可以使用apply和call方法以新创建的对象为上下文执行构造函数。
function superstye(age){
this.age=age;
}
function substye(name){
this.name=name;
superstye.call(this,27)
}
const instance1 =new substye("小红")
console.log(instance1.age)//27
console.log(instance1)//substye { name: '小红', age: 27 }
缺点:必须在构造函数内定义方法,因此函数不能复用
组合式继承
组合继承综合了原型链和盗用构造函数。使用原型链继承原型的属性和方法,而通过盗用构造函数继承实例属性。
function superstye(name){
this.name=name;
this.colors=["red","bule","green"];
}
superstye.prototype.sayname=function(){
console.log(this.name)
}
//继承属性
function substye(name,year){
this.year=year;
superstye.call(this,name)
}
//继承方法
substye.prototype=new superstye;
const substye1=new substye("小明",18);
console.log(substye1.colors)//["red","bule","green"
console.log(substye1.sayname())//小明
原型式继承
可以实现信息共享
function object(o){
function f(){};
f.prototype=o;
return new f;
}
object构造函数就是下面Object自身定义Object.create()函数
Object.create()函数和Object.defineProperties()一样
let person={
name:"喜洋洋",
sex:"男",
friends:["sana","suny","luca"]
};
let firstperson=Object.create(person);
firstperson.name="美羊羊"
firstperson.friends.push="Tyle";
let secondperson=Object.create(person);
firstperson.name="沸羊羊";
secondperson.friends.push="sann";
console.log(person.friends)//"sana,suny,luca,tyle,sann"
寄生式继承
它是与原型式继承比较相似的一种继承方式,思路是类似于寄生构造函数和工厂模式:创建一个实现继承的函数,以某种方式增强对象最后返回这个函数;
function createobject(origin){
let clone=object(origin);
clone.saytime=function(){
console.log("今天是我的生日")
}
return clone;
}
let person={
name:"luca",
people:["1","2"]
}
let person=createobject(person);
person.saytime();//今天是我生日
寄生式组合继承
组合式继承存在效率问题,父类构造函数始总被调用了两次,一次在创建子类原型的时候被调用,一次是在子类构造函数中调用。
function inheritPrototype(subtype,superstype){
let prototype=object(supertype.prototype);//创建对象
prototype.constructor=subType;//增强对象
subtype.prototype=prototype;//赋值对象
}
function superstype(name){
this.name=name;
this.colors=["red","bule","green"];
}
superstye.prototype.sayname=function(){
console.log(this.name)
}
//继承属性
function subtype(name,year){
this.year=year;
superstye.call(this,name)
}
inheritPrototype(subtype,superstype);
核心
function inheritPrototype(subtype,superstype){
let prototype=object(supertype.prototype);//创建对象
prototype.constructor=subType;//增强对象
subtype.prototype=prototype;//赋值对象
}
\