【JS】JS中的继承

1.原型链继承

function SuperType() {
    this.property = true;  
}
SuperType.prototype.getSuperValue = function() {
    return this.property;
}
function SubType() {
    ths.subproperty = false;
}
SubType.prototype = new SuperType();      //  实现继承
SubType.prototype.getSubValue = function() {
    return this.subproperty;
}
var instance = new SubType();
console.log(instance.getSuperValue());      //  true

原理:让SuperType的实例成为子类的原型对象,子类的实例拥有了父类的属性和方法。但也有弊端,如果父类的属性是引用类型,这将导致共享的属性被改变的时候,全部的属性将被改变,我们一下代码。

function SuperType() {
    this.property = [1,2,3]; 
}
SuperType.prototype.getSuperValue = function() {
    return this.property;
}
function SubType() {
    ths.subproperty = false;
}
SubType.prototype = new SuperType();      //  实现继承
SubType.prototype.getSubValue = function() {
    return this.subproperty;
}
var instance1 = new SubType();
var instance2 = new SubType();
instance1.property.push(4);
console.log(instance1.property);      //  [1,2,3,4]
console.log(instance2.property);      //  [1,2,3,4]

我们修改一处的实例属性,两个实例的属性都会被修改,因为这个属性是共享的,这也是原型链继承的缺点。

2.构造函数继承

function SuperType(name) {
    this.name = name;
    this.numbers = [1,2,3];
}
function SubType() {
    SuperType.call(this,"Nicholas");
    this.age = 29;
}

var instance1 = new SubType();
var instance2 = new SubType();
instance1.property.push(4);
console.log(instance1.name);      	//  Nicholas
console.log(instance1.age);         //  29
console.log(instance1.numbers);     // [1,2,3,4]
console.log(instance2.numbers);		// [1,2,3]

在子类中调用父类的构造函数,每次实例化时都会新建父类的属性放在新实例中,因此每个实例中的属性都是不一样的,改变一个实例的值不会造成另一个实例的值改变。这个继承方式的缺点是方法的定义不能复用。

3.组合继承

这个方法将原型链继承和构造函数继承结合到一起,融合了他们各自的优点。

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);
    this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function() {
    console.log(this.age);
}

var instance1 = new SubType("Nicholas", 29);
var instance2 =new SubType("Greg", 27);
instance1.colors.push("black");
console.log(instance1.colors);       //  red,blue,green,black
console.log(instance2.colors);       //  red,blue,green
instance1.sayName();                  //  Nicholas
instance2.sayName();                  //  Greg
instance1.sayAge();                     //  29
instance2.sayAge();                     //  27  

4.class继承

ES6中可以通过class创建对象,通过关键字extends继承。

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

class ColorPoint extends Point {
  constructor(x, y, color) {
    this.color = color; // ReferenceError
    super(x, y);
    this.color = color; // 正确
  }
}

在ES6的继承中,子类一定要重写父类的构造函授的方法,否则会报错。

猜你喜欢

转载自blog.csdn.net/jzq950522/article/details/88235754