ECMAScript 5 对象有一个称为[[Class]]
. 这是 ES5 中最接近您所要求的内容。您可以通过[[Class]]
以下方式访问Object.prototype.toString
:
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); // => "???"