MST

星途 面试题库

面试题:JavaScript构造函数与this在复杂场景下的深入理解

考虑以下场景:有一个构造函数`Parent`,其内部定义了一些方法和属性,这些方法中使用了`this`。然后创建了一个`Child`构造函数继承自`Parent`。现在在`Child`的实例方法中,需要以一种安全且高效的方式调用`Parent`的方法,并根据不同的调用上下文确保`this`的指向正确。另外,在严格模式下,上述操作可能会遇到哪些问题?请编写完整的代码示例并详细解释每一步,包括如何处理`this`指向问题以及严格模式下的特殊情况。
25.8万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
// 定义Parent构造函数
function Parent() {
    // Parent的属性
    this.value = 'parent value';
    // Parent的方法
    this.getInfo = function() {
        return `Value from Parent: ${this.value}`;
    };
}

// 定义Child构造函数并继承自Parent
function Child() {
    // 调用Parent构造函数,确保Child实例能继承到Parent的属性
    Parent.call(this);
    // Child自身的属性
    this.childValue = 'child value';
}
// 设置Child的原型为Parent的实例,实现继承
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

// Child的实例方法
Child.prototype.getChildInfo = function() {
    // 以安全且高效的方式调用Parent的方法,并确保this指向正确
    const parentInfo = Parent.prototype.getInfo.call(this);
    return `${parentInfo}, and Child value: ${this.childValue}`;
};

// 创建Child的实例
const child = new Child();
console.log(child.getChildInfo());

// 严格模式下的情况
// 在严格模式下,如果没有正确处理this的指向,直接调用Parent的方法可能会导致this为undefined
// 例如,以下代码在严格模式下会报错
// function Child() {
//     'use strict';
//     // 没有正确设置this指向,直接调用Parent的方法会出错
//     const badCall = Parent.prototype.getInfo(); 
//     // Uncaught TypeError: Cannot read property 'value' of undefined
// }

代码解释

  1. Parent构造函数:定义了value属性和getInfo方法,getInfo方法使用了this来访问value属性。
  2. Child构造函数:通过Parent.call(this)调用Parent构造函数,将Parent的属性和方法绑定到Child的实例上,确保Child实例能继承到Parent的属性。
  3. 设置原型链Child.prototype = Object.create(Parent.prototype)Child的原型设置为Parent原型的实例,从而实现继承。同时,Child.prototype.constructor = Child确保Child实例的constructor属性指向Child构造函数。
  4. Child的实例方法getChildInfo方法中,通过Parent.prototype.getInfo.call(this)以安全的方式调用ParentgetInfo方法,并将this正确指向Child的实例,这样getInfo方法就能正确访问Child实例的属性。
  5. 严格模式下的问题:在严格模式下,如果没有正确设置this的指向,直接调用Parent的方法(如Parent.prototype.getInfo())会导致thisundefined,因为严格模式下不会自动将全局对象作为this的默认值,从而引发错误。所以在严格模式下,必须使用callapplybind等方法来正确设置this的指向。