這是 JavaScript 定義的全域運作方式,也是開發者最常用的手段。優點是使用簡單好記,缺點是無法有效分辨 object、null、array、regexp 與自訂物件。
var str = 'str';
var arr = ['1', '2'];
var num = 1;
var bool = true;
var obj = { name: 'test' };
var nullObj = null;
var undefinedObj = undefined;
var reg = /reg/;
function fn() { alert('this is a function'); }
function User(name) { this.name = name; }
var user = new User('user');
console.log(typeof (str));
console.log(typeof (arr));
console.log(typeof (num));
console.log(typeof (bool));
console.log(typeof (obj));
console.log(typeof (nullObj));
console.log(typeof (undefinedObj));
console.log(typeof (reg));
console.log(typeof (fn));
console.log(typeof (user));
輸出:
string object number boolean object object undefined object function object
陣列、正則、自訂物件、null 全部塌成 object,這正是它無力判斷細節型別的證據。
這個方法支援絕大多數型別的判斷,jQuery 內部封裝的型別判斷用的就是它。看起來有點繞,我們拆成兩層來看。
a.fun().call(b) 的意思是:讓物件 b 取代 a,然後執行 a 的 fun 函式。寫個例子:
function Class1() {
this.name = "class1";
this.showNam = function () {
alert(this.name);
}
}
function Class2() {
this.name = "class2";
}
var c1 = new Class1();
var c2 = new Class2();
c1.showNam.call(c2);
輸出是 class2 而不是 class1,這就等同於方法借用。所以 Object.prototype.toString().call(param) 的效果,其實就是「用 param 作為 this 去執行 Object 的 toString」。那為什麼不直接寫 param.toString()?答案就在下一節。
Object 是所有 JavaScript 物件的祖先,它提供所有物件通用的功能。prototype 則回傳一個原型的參照,可以動態為原型添加方法與屬性:
function myClass() {
this.name = "class";
this.showName = function () {
alert(this.name);
}
}
var obj = new myClass();
obj.showName();
myClass.prototype.showNameContact = function () {
alert("prototype test" + this.name);
}
obj.showNameContact();
分別輸出 class 與 prototype test class。原本建構子裡並沒有 showNameContact,透過 prototype 就能動態掛上去。
關鍵在於:toString() 被各類別覆寫過了。String、Array、Boolean、RegExp、Number、Function 都繼承自 Object,也都重寫了自己的 toString(),所以直接呼叫 param.toString() 走的是覆寫版本,拿不到型別資訊。我們要的是 Object 身上那個「原版」的 toString()。
ES3 中 Object.prototype.toString 的步驟是:
1. 取得 this 物件的 [[Class]] 內部屬性值。
2. 把 "[object "、第一步的結果、以及 "]" 串接成新字串。
3. 回傳第二步的結果。
ES3 並未明列 [[Class]] 有幾種值,但統計原生物件可得 10 種:"Array"、"Boolean"、"Date"、"Error"、"Function"、"Math"、"Number"、"Object"、"RegExp"、"String"。所以輸出就是 [object Array]、[object Boolean] 這樣的格式。
ES5.1 的規範寫得更細,步驟變成:
1. 若 this 為 undefined,回傳 "[object Undefined]"。
2. 若 this 為 null,回傳 "[object Null]"。
3. 讓 O 成為 ToObject(this) 的結果。
4. 讓 class 成為 O 的內部屬性 [[Class]] 值。
5. 回傳 "[object "、class 與 "]" 串接後的新字串。
比 ES3 多了前三步。第 1、2 步屬於新規則,因為 "Undefined" 與 "Null" 並不屬於 [[Class]] 的取值。此外可回傳的型別增至 "Arguments"、"Array"、"Boolean"、"Date"、"Error"、"Function"、"JSON"、"Math"、"Number"、"Object"、"RegExp"、"String"——arguments 物件的 [[Class]] 從 Object 變成 Arguments,並新增了全域物件 JSON。
回傳字串中的 class 名稱首字母是大寫,像 JSON 甚至全大寫。為了避免大小寫造成誤判,實務上建議統一轉小寫再比對:
Object.prototype.toString.call(param).toLowerCase()