的ECMAScript 5對象具有被稱爲[[Class]]
內部屬性。這是ES5中最接近你要求的東西。您可以通過訪問Object.prototype.toString
[[Class]]
如下:
function getClassOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
getClassOf([ ]); // => "Array"
getClassOf(new Date()); // => "Date"
getClassOf(function() { }); // => "Function"
getClassOf(3); // => "Number"
getClassOf(true) // => "Boolean"
getClassOf(document.createElement('div')); // => "HTMLDivElement"
getClassOf(Math); // => "Math"
getClassOf(null); // => "Null"
getClassOf(undefined); // => "Undefined"
getClassOf({ x: 1 }); // => "Object"
此行爲是充分確定哪些來自其他幀中的對象至關重要。
但是,它不適用於用戶定義的構造函數。使用用戶定義的構造函數創建的對象具有[[Class]]
"Object"
。
function Foo() { }
var foo = new Foo();
getClassOf(foo); // => "Object"
它看起來像ECMAScript的6可能要延長是怎麼通過Object.prototype.toString
返回,這樣getClassOf(foo)
可能是"Foo"
通過@@toStringTag
符號的能力。
有關即將推出的標準的更多信息,請參閱https://mail.mozilla.org/pipermail/es-discuss/2012-September/025344.html。
你可以創建自己的功能,做你想做的是這樣的:
function getTypeOf(value) {
// Return "null" for null.
if (value === null) return 'null';
// Return primitive types.
var type = typeof value;
if (type != 'object') return type;
// Return [[Class]] if available for objects.
type = Object.prototype.toString.call(value).slice(8, -1);
if (type != 'Object') return type;
// Return "Object" if it wasn't created with another constructor.
var proto = Object.getPrototypeOf(value);
if (proto == Object.prototype)
return 'Object';
// Return the constructor name if constructor hasn't been
// modified on the object.
if (value.constructor && proto === value.constructor.prototype)
return value.constructor.name;
// Return the constructor name if constructor hasn't been
// modified on the prototype.
if (proto.constructor && proto === proto.constructor.prototype)
return proto.constructor.name;
// Return "???" if the type is indeterminable.
return '???';
}
例子:
getTypeOf([ ]); // => "Array"
getTypeOf(new Date()); // => "Date"
getTypeOf(function() { }); // => "Function"
getTypeOf(3); // => "number"
getTypeOf(true) // => "boolean"
getTypeOf(document.createElement('div')); // => "HTMLDivElement"
getTypeOf(Math); // => "Math"
getTypeOf(null); // => "null"
getTypeOf(undefined); // => "undefined"
getTypeOf({ x: 1 }); // => "Object"
function Foo() { }
var foo = new Foo();
getTypeOf(foo); // => "Foo"
// If the constructor property is changed, still works.
foo.constructor = function FakeConstructor() { };
getTypeOf(foo); // => "Foo"
// If the constructor property AND the prototype's constructor is
// changed, result is "???".
foo.constructor = function FakeConstructor() { };
Foo.prototype.constructor = function FakeConstructor2() { };
getTypeOf(foo); // => "???"
沒有,有沒有新的運營商。他們考慮修復ES6的'typeof'運算符,以便它會返回'「null」'而不是''object'',但是因爲它會打破太多的代碼而退縮。 –
不知道如果可以添加一個新的操作符,例如調用它'pseudoClassOf'或'typeOrClassOf',那麼它可能是有意義的 –
添加新操作符的麻煩是任何代碼都有一個變量,相同的名字會突然中斷。由於JS被廣泛使用,並且由於仍有許多舊代碼仍在使用中,所以他們對可能會破壞腳本的更改非常敏感。因此,他們試圖堅持當前的保留字。 –