[J框架知識掃盲]之Object.prototype.toString.call()

用過Jquery的朋友都知道,Jquery是通過Object.prototype.toString.call還判斷對象的類型的,那究竟如何做呢?

 

來到http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2的一段話:

 

Object.prototype.toString ( )

 

When the toString method is called, the following steps are taken:

 

1.If the this value is undefined, return "[object Undefined]".

2.If the this value is null, return "[object Null]".

3.Let O be the result of calling ToObject passing the this value as the argument.

4.Let class be the value of the [[Class]] internal property of O.

5.Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

翻譯:

1.如果this的值爲undefined,則返回"[object Undefined]".

2.如果this的值爲null,則返回"[object Null]".

3.讓O成爲調用ToObject(this)的結果.

4.讓class成爲O的內部屬性[[Class]]的值.

5.返回三個字符串"[object ", class, 以及 "]"連接後的新字符串.

 

因此通過調用後Object.prototype.toString.call(),都會返回 [object class]的樣式,我們可以先記錄起這些樣式,反過來判斷。

var class2type = {},     //用於記錄[object class]樣式
objs = "Boolean Number String Function Array Date RegExp Null Undefined".split(" ");
for (var i = 0, l = objs.length; i < l; i++) {
     class2type[ "[object " + objs[i] + "]" ] = objs[i].toLowerCase();
}

function type(obj) {
     return class2type[ Object.prototype.toString.call(obj) ] || "object";
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章