MST

星途 面试题库

面试题:JavaScript 逻辑操作符边界条件之原型链与逻辑短路

在JavaScript中,定义构造函数A,其原型上有属性propA。定义构造函数B继承自A,在B的实例化对象b中,当使用逻辑操作符(b.propA && b.otherProp)时(假设otherProp不存在),会发生什么?如何利用逻辑操作符的边界条件来优雅处理这种情况并保证代码不报错,解释你的思路。
50.3万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
  1. 发生的情况
    • 当执行 b.propA && b.otherProp 时,由于 b 继承自 Ab.propA 可以从 A 的原型链上找到。但是 b.otherProp 不存在,这会导致 b.otherProp 的值为 undefined
    • 逻辑与操作符 && 是短路操作符,它会先计算 b.propA,如果 b.propA 为真值(在JavaScript中,除了 nullundefined0''falseNaN 之外的值都为真值),它会继续计算 b.otherProp。因为 b.otherPropundefined,所以整个表达式 b.propA && b.otherProp 的值为 undefined。同时,在严格模式下,这会导致代码抛出 TypeError 错误,因为不能在 undefined 上进行属性访问(如果 b.propA 为假值,表达式不会计算 b.otherProp,也就不会报错)。
  2. 优雅处理的方法及思路
    • 方法一:使用可选链操作符(?.
      • 在现代JavaScript中,可以使用可选链操作符来优雅地处理这种情况。代码如下:
function A() {}
A.prototype.propA = 'value of propA';
function B() {}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
const b = new B();
// 使用可选链操作符
const result = b.propA && b?.otherProp;
console.log(result);
 - 思路:可选链操作符 `?.` 会在尝试访问 `otherProp` 之前,先检查 `b` 是否为 `null` 或 `undefined`。如果 `b` 是有效的对象,才会尝试访问 `otherProp`。这样就避免了 `b` 为 `null` 或 `undefined` 时访问属性导致的错误。即使 `b.otherProp` 不存在,也不会报错,整个表达式会返回 `undefined`。
  • 方法二:使用 hasOwnProperty 检查
function A() {}
A.prototype.propA = 'value of propA';
function B() {}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
const b = new B();
// 使用 hasOwnProperty 检查
const result = b.propA && b.hasOwnProperty('otherProp')? b.otherProp : undefined;
console.log(result);
 - 思路:`hasOwnProperty` 方法用于检查对象自身是否包含指定的属性。通过先检查 `b` 是否有 `otherProp` 属性,只有在存在该属性时才访问它,这样可以避免因访问不存在属性而导致的错误。如果 `b` 没有 `otherProp` 属性,整个表达式返回 `undefined`。