js 的继承

231 阅读2分钟

构造函数,原型,实例 之间的关系

  • 每个构造函数都有一个原型 : Function.prototype
  • 每个原型都有执行构造函数的指针 Function.prototype .constructor = Function
  • 每一个实例都有一个指向指向原型的指针 A.proto = Function.prototype

继承的实现

  • 原型继承

缺点: 所有的实例会共享父类的属性,导致一个改变全部改变
优点 : 可以继承父类原型的方法

1. function parent (name ){
    this.mame = name;
    this.color = ['1','2','3']
}
parent.prototype .say = function(){
    console.log('parent',this.name)
}

function son (name,age){
    this.name = name ;
    this.age= age;
}
son.prototype = new parent('parent');
son.prototype .constructor = son;
var look = new son('kk',20);
look.color;// ['1','2','3']
look.color.push('4')// ['1','2','3','4']
var look2 = new son();
look2.color;// ['1','2','3','4']



  • 构造函数继承

在子类中执行父类的构造函数,使得父类的this 指向子类的实例化对象,在执行父类构造函数时,实例将得到父类的属性和方法
缺点:无法继承父类原型的方法
优点: 不会使得一个改变而改变所有的实例

 function parent (name ){
    this.mame = name;
    this.color = ['1','2','3']
}
parent.prototype .say = function(){
    console.log('parent',this.name)
}

function son (name,age){
    parent.call(this);
  
    this.name = name ;
    this.age= age;
}
var look = new son();
look.say();//VM805:1 Uncaught TypeError: look.say is not a function at <anonymous>:1:6
look.color;//["1", "2", "3"]
look.color.push('4');["1", "2", "3",'4']
var look2 = new son()
look2.color; //[1,2,3]

  • 组合式继承

使用原型链和构造函数一起实现

 function parent (name ){
    this.mame = name;
    this.color = ['1','2','3']
}
parent.prototype .say = function(){
    console.log('parent',this.name)
}

function son (name,age){
    parent.call(this);//第二次调用父类的构造函数
    this.name = name ;
    this.age= age;
}
son.prototype = new parent(); //第一次调用父类的构造函数
son.prototype.constructor = son;
var look = new son();
look.say();//VM805:1 Uncaught TypeError: look.say is not a function at <anonymous>:1:6
look.color;//["1", "2", "3"]
look.color.push('4');["1", "2", "3",'4']
var look2 = new son()
look2.color; //[1,2,3]
  • 寄生式继承

解决组合继承的缺点:两次调用父类的构造函数

 function parent (name ){
    this.mame = name;
    this.color = ['1','2','3']
}
parent.prototype .say = function(){
    console.log('parent',this.name)
}

function son (name,age){
    parent.call(this);
    this.name = name ;
    this.age= age;
}
//创建一个对象
son.prototype = Object.create(person.prototype)
son.prototype.construtor = son
var look = new son();
look.say();//VM805:1 Uncaught TypeError: look.say is not a function at <anonymous>:1:6
look.color;//["1", "2", "3"]
look.color.push('4');["1", "2", "3",'4']
var look2 = new son()
look2.color; //[1,2,3]