2011-05-03 14 views

回答

4

它是錯誤的,因爲intanceOf [原文如此]是undefined,而不是對String構造函數的引用。

instanceOf操作,不是一個實例方法或屬性,並且使用這樣的:

"string" instanceof String 

但爲文本字符串不使用String構造函數創建一個String object這將返回false。

讓您真正想要做的是使用type操作

typeof "string" == "string" 
+0

沒錯!如果你明確地調用了String構造函數,instanceof就可以工作:var x = new String('myname'); – Jad 2011-05-03 09:23:06

1

使用}這種可能不是一個好主意。

typeof運算符(帶有 的instanceof一起)或許是JavaScript的最大 設計缺陷,因爲它是 被徹底打破近。

參見:http://bonsaiden.github.com/JavaScript-Garden/#types.typeof

而是使用Object.prototype.toString像這樣:

function is(type, obj) { 
    var clas = Object.prototype.toString.call(obj).slice(8, -1); 
    return obj !== undefined && obj !== null && clas === type; 
} 

is('String', 'test'); // true 
is('String', new String('test')); // true 
相關問題