2011-08-12 135 views
5

我可以使用構造函數屬性來檢測JavaScript中的類型嗎? 或者有什麼我應該知道的。我可以使用constructor.name來檢測JavaScript中的類型嗎

例如:var a = {}; a.constructor.name; //outputs Object

var b = 1; b.constructor.name; //outputs Number

var d = new Date(); d.constructor.name; //outputs Date not Object

var f = new Function(); f.constructor.name; //outputs Function not Object

只有在使用它的參數arguments.constructor.name; //outputs Object like first example

我看到使用往往開發商:Object.prototype.toString.call([])

Object.prototype.toString.call({})

回答

5

您可以使用typeof,但它返回misleadingresults有時。相反,使用Object.prototype.toString.call(obj),它使用該對象的內部[[Class]]屬性。你甚至可以做一個簡單的包裝它,所以它的作用類似於typeof

function TypeOf(obj) { 
    return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); 
} 

TypeOf("String") === "string" 
TypeOf(new String("String")) === "string" 
TypeOf(true) === "boolean" 
TypeOf(new Boolean(true)) === "boolean" 
TypeOf({}) === "object" 
TypeOf(function(){}) === "function" 

不要使用obj.constructor,因爲它可以改變的,雖然你可能能夠使用instanceof,看它是否是正確的:

function CustomObject() { 
} 
var custom = new CustomObject(); 
//Check the constructor 
custom.constructor === CustomObject 
//Now, change the constructor property of the object 
custom.constructor = RegExp 
//The constructor property of the object is now incorrect 
custom.constructor !== CustomObject 
//Although instanceof still returns true 
custom instanceof CustomObject === true 
+0

'constructor.name'在IE中不起作用。 – gruentee

+0

@gruentee [引用需要] 在IE11中工作得很好 –

1

您可以使用typeof 例:typeof("Hello")

+0

的typeof不需額外居然如此精確,因爲'警告(ty​​peof運算新的Number())// Object' – veidelis

+0

同意,因爲JavaScript是不是你cannt預計其typeof運算是精確類型化的語言:) – Ankur

+1

無,JavaScript是一種鬆散類型的語言。 – veidelis

相關問題