- 发生的情况:
- 当执行
b.propA && b.otherProp
时,由于 b
继承自 A
,b.propA
可以从 A
的原型链上找到。但是 b.otherProp
不存在,这会导致 b.otherProp
的值为 undefined
。
- 逻辑与操作符
&&
是短路操作符,它会先计算 b.propA
,如果 b.propA
为真值(在JavaScript中,除了 null
、undefined
、0
、''
、false
和 NaN
之外的值都为真值),它会继续计算 b.otherProp
。因为 b.otherProp
是 undefined
,所以整个表达式 b.propA && b.otherProp
的值为 undefined
。同时,在严格模式下,这会导致代码抛出 TypeError
错误,因为不能在 undefined
上进行属性访问(如果 b.propA
为假值,表达式不会计算 b.otherProp
,也就不会报错)。
- 优雅处理的方法及思路:
- 方法一:使用可选链操作符(
?.
):
- 在现代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`。