我建立了一個JavaScript對象,可是如何肯定該對象的類呢? javascript
我想要相似於Java的.getClass()
方法。 java
JavaScript中沒有與Java的getClass()
徹底相同的對象。 大多數狀況下,這是因爲JavaScript是基於原型的語言 ,而不是Java是基於類的 語言 。 git
根據您須要getClass()
的不一樣,JavaScript中有幾個選項: github
typeof
instanceof
obj.
constructor
func.
prototype
, proto
。 isPrototypeOf
一些例子: gulp
function Foo() {} var foo = new Foo(); typeof Foo; // == "function" typeof foo; // == "object" foo instanceof Foo; // == true foo.constructor.name; // == "Foo" Foo.name // == "Foo" Foo.prototype.isPrototypeOf(foo); // == true Foo.prototype.bar = function (x) {return x+x;}; foo.bar(21); // == 42
注意:若是使用Uglify編譯代碼,它將更改非全局類名。 爲了防止這種狀況,Uglify有一個--mangle
參數,您能夠使用gulp或grunt設置爲false。 函數
Javascript是一種無類語言:沒有類能夠像Java中同樣靜態地定義類的行爲。 JavaScript使用原型而不是類來定義對象屬性,包括方法和繼承。 使用JavaScript中的原型能夠模擬許多基於類的功能。 grunt
您能夠使用構造函數屬性獲取對建立對象的構造函數的引用: spa
function MyObject(){ } var obj = new MyObject(); obj.constructor; // MyObject
若是須要在運行時確認對象的類型,則能夠使用instanceof運算符: prototype
obj instanceof MyObject // true
在javascript中,沒有任何類,但我認爲您但願構造函數名稱和obj.constructor.toString()
會告訴您所需的內容。 code
此函數從Object.prototype.toString.call(someObject)
[object class]
"undefined"
, "null"
或"class"
。
function getClass(obj) { if (typeof obj === "undefined") return "undefined"; if (obj === null) return "null"; return Object.prototype.toString.call(obj) .match(/^\[object\s(.*)\]$/)[1]; } getClass("") === "String"; getClass(true) === "Boolean"; getClass(0) === "Number"; getClass([]) === "Array"; getClass({}) === "Object"; getClass(null) === "null"; // etc...