對象屬性的增刪查改是 JavaScript 的地基。看似簡單的操作背後有不少細節:delete 到底刪了什麼、in 和 hasOwnProperty 有何差別、for...in 為什麼會枚舉出意料之外的鍵。本文逐一梳理。
delete 運算符用來移除對象屬性:
delete person.age;
delete person['age']; // 兩種寫法等價
delete 只切斷屬性與宿主對象的聯繫,不影響值的引用。
var a = { p: { x: 1 } };
var b = a.p;
console.log(a.p.x); // 1
delete a.p;
console.log(a.p); // undefined
console.log(b.x); // 1,b 依然持有那個對象
delete 只能刪除自有屬性,不能刪除繼承而來的屬性。要移除繼承屬性,必須到原型對象上操作,但這會影響所有繼承自該原型的對象。
下面是一個手寫的簡單繼承工具,用來驗證上述行為:
function inherit(p) {
if (p == null) { throw TypeError(); }
if (Object.create) { return Object.create(p); }
var t = typeof p;
if (t !== "object" && t !== "function") { throw TypeError(); }
function f() { }
f.prototype = p;
return new f();
}
var obj = { x: 1 };
var obj1 = inherit(obj);
obj1.y = 2;
console.log(obj1.x, obj1.y); // 1 2
delete obj1.x; // 刪不掉,x 是繼承而來的
delete obj1.y; // 可以刪,y 是自有屬性
console.log(obj1.x, obj1.y); // 1 undefined
只有可配置(configurable)的屬性才能被 delete。
delete Object.prototype; // 失敗,不可配置
var x = 1;
delete this.x; // 失敗
this.y = 1;
delete y; // 可以
左操作數是字符串(或可轉字符串),右操作數是對象。它會同時檢查自有屬性和繼承屬性。
var data = [5, 6, 7];
"0" in data; // true
1 in data; // true,1 會轉成 "1"
"4" in data; // false,下標最大是 2
var obj = { x: 1 };
"x" in obj; // true
"y" in obj; // false
"toString" in obj; // true,繼承自原型
只檢查自有屬性:
var obj = { x: 1 };
obj.hasOwnProperty("x"); // true
obj.hasOwnProperty("y"); // false
obj.hasOwnProperty("toString"); // false,它是繼承來的
是 hasOwnProperty 的加強版,要求屬性既是自有的、又是可枚舉的:
var obj = { x: 1 };
obj.propertyIsEnumerable("x"); // true
obj.propertyIsEnumerable("y"); // false
obj.propertyIsEnumerable("toString"); // false
Object.prototype.propertyIsEnumerable("toString"); // false,原型上的方法不可枚舉
var obj = { x: 1 };
obj.x !== undefined; // true
obj.y !== undefined; // false
obj.toString !== undefined; // true
這種寫法有個前提:屬性的值不能本身就是 undefined,否則會誤判。
var obj = { x: 1, y: 2 };
for (p in obj) {
console.log(p); // x y
console.log(obj.p); // undefined undefined,p 是字符串鍵
console.log(obj[p]); // 1 2
}
for...in 會遍歷原型鏈上所有可枚舉的屬性,這也是它經常被替換成 Object.keys() 或 for...of 的原因。
每個對象都有原型(prototype)、類(class)和可擴展性三個屬性。判斷原型關係用 isPrototypeOf():
var p = { x: 1 };
var o = Object.create(p);
p.isPrototypeOf(o); // true
Object.prototype.isPrototypeOf(o); // true
Object.prototype.isPrototypeOf(p); // true
instanceof 與之類似,左操作數是對象,右操作數是類:
p instanceof Object; // true
new Date() instanceof Date; // true
new Date() instanceof Object; // true
new Date() instanceof Number; // false
對象的 class 屬性是個字符串。調用 toString() 會返回 [object class] 形式,截取中間部分即可:
function classOf(obj) {
if (obj === null) { return "Null"; }
if (obj === undefined) { return "Undefined"; }
return Object.prototype.toString.call(obj).slice(8, -1);
}
classOf(1); // "Number"
classOf(""); // "String"
classOf(null); // "Null"
classOf(false); // "Boolean"
classOf({}); // "Object"
classOf([]); // "Array"
classOf(new Date()); // "Date"
注意不能直接寫 (1).toString() 以外的形式如 1.toString()——語法解析器會把點號當作小數點的一部分而報錯。同時,對象自身重寫 toString 後結果會失真,所以要用 Object.prototype.toString.call() 繞過。