js继承方式

时间:2023-03-09 17:38:52
js继承方式

1.原型链

  • 实现的本质是重写原型对象,代之以一个新类型的实例;
  • 给原型添加方法的代码一定放在替换原型的语句之后;
  • 不能使用对象字面量查收能见原型方法,这样会重写原型链。
  • 缺点:包含引用类型值的原型属性会被所有实例共享;在创建子类型时,不能向超类型的构造函数中传递参数。

2.借用构造函数

  • 在子类型构造函数的内部调用超类型构造函数;
  • 可以在子类型构造函数中向超类型构造函数传递参数;
  • 缺点:方法都在构造函数中定义,无法函数复用,且在超类型的原型中定义的方法对子类型不可见的。

3.组合继承

  • 使用原型链实现对原型属性和方法的继承,借用构造函数实现对实例属性的继承;
  • 缺点:无论什么情况下都会调用两次超类型构造函数(一次在查收能见子类型原型时,一次是在子类型构造函数内部)
  • function Parent(name) {
    this.name = name;
    this.arr = [1, 2, 3];
    }
    Parent.prototype.sayName = function(){
    console.log(this.name);
    };
    function Child(name, age) {
    Parent.call(this, name); // 第二次调用Parent
    this.age = age;
    }
    Child.prototype = new Parent(); // 第一次调用Parent
    Child.prototype.constructor = Child;
    Child.prototype.sayAge = function() {
    console.log(this.age);
    };
    var a = new Child('cc', 20);

4.原型式继承

  • Object.create()规范了原型式继承,可以接收两个参数(用作新对象原型的对象,为新对象定义额外属性的对象);
  • 缺点:包含引用类型值的属性始终会共享相应的值。

5.寄生式继承

  • 创建一个仅用于封装继承过程的函数,在函数内部增强对象,最后返回对象;
  • 缺点:不能函数复用而降低效率。

6.寄生组合式继承

  • 通过借用构造函数继承属性,通过原型链继承方法;
  • 不必为了指定子类型的原型调用超类型的构造函数,我们只需要超类型原型的一个副本即可;使用寄生式继承来继承超类型原型,再将结果指定给子类型原型;
  • 只调用了一次超类型构造函数。
  • function inheritPrototype(child, parent) {
    var prototype = Object.create(parent.prototype);
    prototype.constructor = child;
    child.prototype = prototype;
    }
    function Parent(name) {
    this.name = name;
    this.arr = [1, 2, 3];
    }
    Parent.prototype.sayName = function(){
    console.log(this.name);
    };
    function Child(name, age) {
    Parent.call(this, name);
    this.age = age;
    }
    inheritPrototype(Chid, Parent);
    Child.prototype.sayAge = function() {
    console.log(this.age);
    };
    var a = new Child('cc', 20);

--摘自《javascript高级程序设计》

补充(es6中的继承):

class Sup{
constructor(x, y) {
this.x= x;
this.y=y;
}
toString() {
return this.x+' '+this.y;
}
} class Sub extends Sup {
constructor(x, y, color) {
super(x, y); // 调用父类的constructor(x, y)
this.color = color;
}
toString() {
return this.color + ' ' + super.toString(); // 调用父类的toString()
}
}