【发布时间】:2015-05-26 15:36:58
【问题描述】:
鉴于此:
function SomeType () { return this; }
我怎样才能只用一个字符串来检查一个对象的类型?
如果我有对构造函数的引用,那就太好了,就像这样:
new SomeType() instanceof SomeType; // true
但是如果我想检查类型为String,没有简单的方法检查。
new SomeType() instanceof 'SomeType'; // TypeError
我可以在构造函数转换为字符串后检查它:
function SomeType () { return this; }
/function \bSomeType\b/.test( String(new SomeType().constructor) ); // true
但并非在所有情况下都有效:
var SomeType = function () { return this; }
/function \bSomeType\b/.test( String(new SomeType().constructor) ); // false
对此有什么想法吗?尝试通过 String 验证类型/构造函数是否会被视为反模式?
【问题讨论】:
-
“尝试通过字符串验证类型/构造函数是否会被视为反模式?” 是的。这也是不可能的,正如您在
var SomeType = function () { … };中看到的那样;该构造函数没有名称,因此您无法检查它。 -
@minitech 我也这么认为。我喜欢 JavaScript 的松散类型,直到它伤害到我为止。
标签: javascript types instanceof typeof