interview
advanced-javascript-frontend
JavaScript 中如何实现寄生组合继承

前端 JavaScript 进阶面试题, JavaScript 中如何实现寄生组合继承?

前端 JavaScript 进阶面试题, JavaScript 中如何实现寄生组合继承?

QA

Step 1

Q:: JavaScript 中如何实现寄生组合继承?

A:: 寄生组合继承是 JavaScript 中一种实现继承的方式,旨在避免传统组合继承中的效率问题。具体实现方法如下:

 
function inheritPrototype(subType, superType) {
    var prototype = Object.create(superType.prototype); // 创建对象
    prototype.constructor = subType; // 增强对象
    subType.prototype = prototype; // 指定对象
}
 
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); // 第二次调用 SuperType
    this.age = age;
}
 
inheritPrototype(SubType, SuperType);
 
SubType.prototype.sayAge = function() {
    console.log(this.age);
};
 

这种方式通过 Object.create 创建一个以父类原型为原型的对象,并将这个对象赋值给子类的原型,从而避免了在子类构造函数中第二次调用父类构造函数。

用途

面试中考察寄生组合继承的实现方式,是为了了解候选人对 JavaScript 继承机制的掌握情况。寄生组合继承解决了传统组合继承中的一些效率问题,特别是避免了多次调用父类构造函数带来的不必要开销。在实际生产环境中,当我们需要进行对象继承并且希望优化性能时,会用到这种继承方式。例如,在复杂的面向对象编程中,需要确保子类能够正确继承父类的属性和方法,并且希望提高代码的执行效率。\n

相关问题

🦆
JavaScript 中的原型链是什么?

JavaScript 中的原型链是一种继承机制,它使对象可以共享其他对象的方法和属性。当访问一个对象的属性或方法时,如果这个对象本身没有该属性或方法,那么 JavaScript 会沿着原型链向上查找,直到找到该属性或方法或到达原型链的末端。每个对象都有一个原型对象(通过 __proto__ 指向),而这个原型对象也有自己的原型,形成链式结构。例如:

 
function Person(name) {
    this.name = name;
}
 
Person.prototype.getName = function() {
    return this.name;
};
 
var person1 = new Person('Alice');
console.log(person1.getName()); // Alice
console.log(person1.__proto__ === Person.prototype); // true
 
🦆
JavaScript 中的 call 和 apply 方法有什么区别?

callapply 方法都是用来改变函数内部 this 指向的,但它们的区别在于传递参数的方式不同。call 方法接受的是参数列表,而 apply 方法接受的是一个参数数组。

例如:

 
function greet(greeting, punctuation) {
    console.log(greeting + ', ' + this.name + punctuation);
}
 
var person = { name: 'Alice' };
 
// 使用 call
greet.call(person, 'Hello', '!'); // Hello, Alice!
 
// 使用 apply
greet.apply(person, ['Hi', '?']); // Hi, Alice?
 

在这个例子中,callapply 都将 this 指向了 person 对象,但 call 是逐个传递参数,而 apply 是传递数组。

🦆
什么是 JavaScript 闭包?

闭包是指那些能够访问自由变量的函数。换句话说,闭包可以记住并访问它的词法作用域,即使这个函数是在其词法作用域之外执行。

例如:

 
function outerFunction(outerVariable) {
    return function innerFunction(innerVariable) {
        console.log('Outer variable: ' + outerVariable);
        console.log('Inner variable: ' + innerVariable);
    };
}
 
const newFunction = outerFunction('outside');
newFunction('inside');
 

在这个例子中,innerFunction 是一个闭包,它记住了 outerFunctionouterVariable,即使 outerFunction 已经执行结束。