| 方法 | 語法 | 檢測範圍 | 返回值 | 注意事項 |
|---|---|---|---|---|
| in 操作符 | 'prop' in obj | 自有屬性 + 繼承屬性 | boolean | 屬性值為 undefined 也返回 true |
| hasOwnProperty | obj.hasOwnProperty('prop') | **僅自有屬性** | boolean | 不檢測原型鏈;可被覆蓋(極少見) |
| undefined 比較 | obj.prop !== undefined | 自有 + 繼承 | boolean | ❌ 屬性值為 undefined 時誤判為不存在 |
| 條件判斷 | if (obj.prop) ... | 自有 + 繼承 | boolean | ❌ 假值 (0, '', false, null, undefined, NaN) 均視為不存在 |
var obj = {
x: 1,
y: undefined,
z: 0
};
// 繼承屬性
Object.prototype.inherited = 'from proto';
console.log('--- in ---');
console.log('x' in obj); // true
console.log('y' in obj); // true (值是 undefined 但存在)
console.log('z' in obj); // true
console.log('toString' in obj); // true (繼承)
console.log('--- hasOwnProperty ---');
console.log(obj.hasOwnProperty('x')); // true
console.log(obj.hasOwnProperty('y')); // true
console.log(obj.hasOwnProperty('z')); // true
console.log(obj.hasOwnProperty('toString')); // false (繼承)
console.log('--- !== undefined ---');
console.log(obj.x !== undefined); // true
console.log(obj.y !== undefined); // false ❌ 陷阱!
console.log(obj.z !== undefined); // true
console.log(obj.toString !== undefined); // true
console.log('--- if (obj.prop) ---');
console.log(!!obj.x); // true
console.log(!!obj.y); // false
console.log(!!obj.z); // false ❌ 0 被誤判
console.log(!!obj.toString); // true
// 靜態方法,不受原型鏈污染,語義更清晰
console.log(Object.hasOwn(obj, 'x')); // true
console.log(Object.hasOwn(obj, 'toString')); // false
console.log(Object.hasOwn(obj, 'y')); // true (值為 undefined 但存在)
// 舊版 polyfill
if (!Object.hasOwn) {
Object.hasOwn = function(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
}
console.log(Reflect.has(obj, 'x')); // true
console.log(Reflect.has(obj, 'toString')); // true (含繼承)
// 等價於 'x' in obj
// 推薦:ES2022
if (Object.hasOwn(obj, 'prop')) { ... }
// 兼容舊環境
if (Object.prototype.hasOwnProperty.call(obj, 'prop')) { ... }
// 或
if ({}.hasOwnProperty.call(obj, 'prop')) { ... } // 更短
if ('prop' in obj) { ... }
// 或
if (Reflect.has(obj, 'prop')) { ... }
// 明確意圖
if (obj.prop !== undefined) { ... } // 允許 0, '', false
if (obj.prop != null) { ... } // 排除 null/undefined,允許 0, '', false
if (obj.prop) { ... } // 僅真值(需明確業務語義)
var dict = Object.create(null); // 無原型,無 toString, hasOwnProperty 等
dict.foo = 'bar';
console.log('foo' in dict); // true
console.log(dict.hasOwnProperty('foo')); // TypeError! dict 沒有此方法
console.log(Object.prototype.hasOwnProperty.call(dict, 'foo')); // true
console.log(Object.hasOwn(dict, 'foo')); // true ✅ 最安全
屬性存在性檢測看似簡單,實則坑多。**默認首選 `Object.hasOwn()` (或 `Object.prototype.hasOwnProperty.call()`) 判斷自有屬性**;需包含繼承用 `in`/`Reflect.has()`;嚴禁用 `!= undefined` 或 `if (obj.prop)` 判斷存在性。寫出語義明確、無隱患的類型檢測代碼,是工程師專業度的體現。