跳到主要内容

Javascript继承的6种方法?

参考答案:

在JavaScript中,有多种方式可以实现继承。以下是其中的六种方法:

  1. 原型链继承:这是JavaScript中最基本的继承方式。子类型的原型被设置为超类型的实例。这样,子类型就能够访问超类型原型上的属性和方法。
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;
};

var instance1 = new SubType();
instance1.getSuperValue(); // true
  1. 借用构造函数继承:在子类型的构造函数中调用超类型的构造函数,这样超类型中的属性就可以被子类型继承了。
function SuperType() {
    this.colors = ["red", "blue", "green"];
}

function SubType() {
    // 继承了SuperType
    SuperType.call(this);
}

var instance1 = new SubType();
instance1.colors.push("black");
console.log(instance1.colors); // ["red", "blue", "green", "black"]

var instance2 = new SubType();
console.log(instance2.colors); // ["red", "blue", "green"]
  1. 组合继承:这是最常用的继承模式,将原型链和借用构造函数的技术组合到一起。
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 = Object.create(SuperType.prototype);
SubType.prototype.constructor = SubType;

SubType.prototype.sayAge = function() {
    console.log(this.age);
};

var instance1 = new SubType("John", 20);
instance1.colors.push("black");
console.log(instance1.colors); // ["red", "blue", "green", "black"]

var instance2 = new SubType("Mary", 22);
console.log(instance2.colors); // ["red", "blue", "green"]

instance1.sayName(); // "John"
instance1.sayAge(); // 20
  1. 原型式继承:通过Object.create()方法创建一个新对象,使用现有的对象作为新创建对象的__proto__。
function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

var person = {
    isHuman: false,
    printIntroduction: function() {
        console.log("My name is " + this.name.toFirstUpper() + ". Am I human? " + this.isHuman);
    }
};

var me = object(person);
me.name = "Matthew";
me.isHuman = true;
me.printIntroduction();
  1. 寄生式继承:在原型式继承的基础上,为对象添加新的属性和方法。
function createAnother(original) {
    var clone = Object.create(original);
    clone.sayHi = function() {
        console.log("hi");
    };
    return clone;
}

var person = {
    isHuman: false,
    printIntroduction: function() {
        console.log("My name is " + this.name.toFirstUpper() + ". Am I human? " + this.isHuman);
    }
};

var anotherPerson = createAnother(person);
anotherPerson.name = "John";
anotherPerson.isHuman = true;
anotherPerson.sayHi(); // "hi"
  1. 寄生组合式继承:通过借用构造函数来继承属性,通过原型链来继承方法。
function SuperType(name) {
    this.name = name;
    this.colors = ["red", "blue", "green"];
}

SuperType.prototype.sayName = function() {