JavaScript 的 typeof 其實相當複雜:它能做的事情很多,同時也留有不少讓人頭疼的怪異行為。本文逐一列出它的用途,並指出其中的問題與可行的替代方案。
閱讀前,最好你已經清楚原始值與物件的差異。
typeof 在兩種情況下會回傳 "undefined":變數沒有被宣告,或變數的值是 undefined。
> typeof undeclaredVariable === "undefined"
true
> var declaredVariable;
> typeof declaredVariable
'undefined'
> typeof undefined
'undefined'
也有別的方式判斷某個值是否為 undefined:
> var value = undefined;
> value === undefined
true
但這種寫法用在未宣告的變數上會拋出異常。只有 typeof 能在不報錯的前提下安全檢測:
> undeclaredVariable === undefined
ReferenceError: undeclaredVariable is not defined
不過要注意,未初始化的變數、沒傳入參數的形參、不存在的屬性都不會有這個問題,因為它們總是可存取的,值就是 undefined:
> var declaredVariable;
> declaredVariable === undefined
true
> (function (x) { return x === undefined }())
true
> ({}).foo === undefined
true
所以,若想檢測一個可能未宣告的全域變數是否存在,也可以寫成 if (window.maybeUndeclaredVariable) {}。
問題:typeof 做這件事顯得繁瑣。可能的解法:也許語言該提供一個專門的運算子,例如:
> defined undeclaredVariable
false
> var declaredVariable;
> defined declaredVariable
false
或者一個用來判斷「是否已宣告」的運算子:
> declared undeclaredVariable
false
> var declaredVariable;
> declared declaredVariable
true
(在 Perl 裡,上面兩個運算子分別對應 defined() 與 exists()。)
問題:如果你想判斷一個值「有被定義過」(不是 undefined 也不是 null),就會撞上 typeof 最有名的一個怪癖:
> typeof null
'object'
這原本是最初 JavaScript 實作留下的 bug,但後來標準就照此規範了。V8 曾經修正並實作過 typeof null === "null",最終證明行不通。
解法:不要用 typeof 做這件事,改寫成一個明確的函數:
function isDefined(x) {
return x !== null && x !== undefined;
}
另一種思路是引入「預設值運算子」,在 myValue 未定義時回傳 defaultValue:
myValue ?? defaultValue
等價於:
(myValue !== undefined && myValue !== null) ? myValue : defaultValue
以及它的賦值簡寫形式:
myValue ??= defaultValue
其實就是這行的縮寫:
myValue = myValue ?? defaultValue
存取嵌套屬性時,這個運算子特別有用。比如 obj.foo.bar,若 obj 或 obj.foo 未定義就會拋錯。有了它,就能在逐層往下走時,遇到第一個 undefined 或 null 就停下:
obj.??foo.??bar
等價於:
(obj === undefined || obj === null) ? obj
: (obj.foo === undefined || obj.foo === null) ? obj.foo
: obj.foo.bar
判斷 x 是否為物件值:
function isObject(x) {
return (typeof x === "function"
|| (typeof x === "object" && x !== null));
}
問題:這段判斷之所以麻煩,是因為 typeof 把函數與物件視為不同型別,而且 typeof null 回傳 "object"。
解法:另一個常見寫法:
function isObject2(x) {
return x === Object(x);
}
這裡有個警告:你可能覺得可以用 instanceof Object,但 instanceof 依賴原型鏈判斷實例關係,那麼沒有原型的物件怎麼辦?
> var obj = Object.create(null);
> Object.getPrototypeOf(obj)
null
obj 確實是個物件,卻不是任何值的實例:
> typeof obj
'object'
> obj instanceof Object
false
實務上你很少遇到這種物件,但它的確存在,也有其用途。順帶一提,Object.prototype 就是唯一一個內建的、沒有原型的物件:
> Object.getPrototypeOf(Object.prototype)
null
> typeof Object.prototype
'object'
> Object.prototype instanceof Object
false
typeof 是查看原始值型別的最佳工具:
> typeof "abc"
'string'
> typeof undefined
'undefined'
問題:你必須時時記得 typeof null 的怪癖。
解法:針對這個特定場景做修正:
function getPrimitiveTypeName(x) {
var typeName = typeof x;
switch (typeName) {
case "undefined":
case "boolean":
case "number":
case "string":
return typeName;
case "object":
if (x === null) {
return "null";
}
default: // 前面的判斷都沒通過
throw new TypeError("參數不是一個原始值: " + x);
}
}
更好的做法是實作一個 getTypeName(),除了回傳原始值的型別,還能回傳物件的內部 [[Class]] 屬性(jQuery 中的 $.type 就是這樣做的)。
> typeof function () {}
'function'
> typeof Object.prototype.toString
'function'
原則上 instanceof Function 也能做這種檢測,看起來還更優雅。但瀏覽器有個怪癖:每個框架(frame)與視窗都有自己的全域變數。因此把某個框架中的物件傳到另一個框架時,instanceof 就會失效,因為兩邊的建構函數並不相同。這也正是 ECMAScript 5 要提供 Array.isArray() 的原因。
上面提到的 getTypeName() 是一個可用的變通做法,但或許還有更根本的方案。
以下幾項,大概是目前 JavaScript 最需要補上、用以分擔 typeof 職責的能力:
isDefined()(例如 Object.isDefined()),可以是函數也可以是運算子。isObject()getTypeName()至於「檢查變數是否已宣告」,這個需求或許還不到需要專屬運算子的程度。