跳到主要内容

简述说出你熟知的 Javascript继承方式 ?

参考答案:

JavaScript 中的继承方式主要有以下几种:

  1. 原型链继承:这是 JavaScript 中最常见的继承方式。每个 JavaScript 对象都有一个原型对象,当试图访问一个对象的属性时,如果对象内部不存在这个属性,那么 JavaScript 会在对象的原型上寻找这个属性,这就是原型链。通过设置子对象的原型为父对象,可以实现继承。
function Parent() {
    this.name = 'parent';
}

function Child() {
    this.type = 'child';
}

Child.prototype = new Parent(); // 将 Child 的原型设置为 Parent 的一个实例

var child = new Child();
console.log(child.name); // 输出 'parent'
  1. 借用构造函数继承:也被称为经典继承或组合继承。这种方式的基本思想是在子类型构造函数的内部调用超类型构造函数。
function Parent() {
    this.name = 'parent';
}

function Child() {
    Parent.call(this); // 调用 Parent 构造函数
    this.type = 'child';
}

var child = new Child();
console.log(child.name); // 输出 'parent'
  1. 组合继承(原型链+借用构造函数):这是 JavaScript 中最常用的继承模式,它结合了原型链和借用构造函数的优点,同时避免了它们的缺点。主要思路是,使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。
function Parent() {
    this.name = 'parent';
    this.play = [1, 2, 3];
}

function Child() {
    Parent.call(this);
    this.type = 'child';
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

var child = new Child();
console.log(child.name); // 输出 'parent'
console.log(child.play); // 输出 [1, 2, 3]
  1. 原型式继承:这种方式是借助 Object.create 方法实现继承。Object.create 方法会创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。
var parent = {
    name: 'parent',
    play: function() {
        console.log('play');
    }
};

var child = Object.create(parent);
child.type = 'child';

console.log(child.name); // 输出 'parent'
child.play(); // 输出 'play'
  1. 寄生式继承:寄生式继承的思路是创建一个仅用于封装继承过程的函数,该函数内部以某种方式来增强对象,最后再像真的是它做了所有工作一样返回对象。
function createAnother(original) {
    var clone = Object.create(original);
    clone.sayHi = function() {
        alert('hi');
    };
    return clone;
}

var parent = {
    name: 'parent',
    play: function() {
        console.log('play');
    }
};

var child = createAnother(parent);
child.type = 'child';

console.log(child.name); // 输出 'parent'
child.play(); // 输出 'play'
child.sayHi(); // 弹出 'hi'
  1. 寄生组合式继承:这是 JavaScript 中最理想的一种继承方式,它结合了组合继承和寄生式继承的优点。主要思路是,通过借用构造函数来继承属性,通过原型链的混成形式来继承方法。
function inheritPrototype(child, parent) {
    var prototype = Object.create(parent.prototype);
    prototype.constructor = child;
    child.prototype = prototype;
}

function Parent() {
    this.name = 'parent';
    this.play = [1, 2, 3];
}

function Child() {
    Parent.call(this);
    this.type = 'child';
}

inheritPrototype(Child, Parent);

var child = new Child();
console.log(child.name); // 输出 'parent'
console.log(child.play); // 输出 [1, 2, 3]

以上就是一些常见的 JavaScript 继承方式,每种方式都有其优点和缺点,需要根据具体的场景和需求来选择使用哪种方式。