Javascript类型的自定义对象

Bja*_*rtN 54 javascript

如何检查我的javascript对象是否属于某种类型.

var SomeObject = function() { }
var s1 = new SomeObject();
Run Code Online (Sandbox Code Playgroud)

在上面的情况下typeof s1将返回"对象".这不是很有帮助.有没有办法检查s1是否为SomeObject类型?

T.J*_*der 74

是的,使用instanceof(MDN链接 | 规范链接):

if (s1 instanceof SomeObject) { ... }
Run Code Online (Sandbox Code Playgroud)


AAr*_*ron 17

无论你做什么,都要避免使用obj.constructor.name或构造函数的任何字符串版本.这很有效,直到你uglify/minify你的代码,然后它全部中断,因为构造函数被重命名为一些模糊的东西(例如:'n'),你的代码仍将执行此操作并且永远不会匹配:

// Note: when uglified, the constructor may be renamed to 'n' (or whatever),
// which breaks this code since the strings are left alone.
if (obj.constructor.name === 'SomeObject') {}
Run Code Online (Sandbox Code Playgroud)

注意:

// Even if uglified/minified, this will work since SomeObject will
// universally be changed to something like 'n'.
if (obj instanceof SomeObject) {}
Run Code Online (Sandbox Code Playgroud)

(顺便说一下,我需要更高的声誉来评论其他有价值的答案)

  • [见这个链接](http://engblog.yext.com/post/js-type-checking).构造函数属性是另一种有趣的方法.继续避免字符串方法. (2认同)

lam*_*345 5

想法从http://phpjs.org/functions/get_class/偷走,由SeanJA发布.翻录下来只处理对象而不需要正则表达式:

function GetInstanceType(obj)
{
    var str = obj.constructor.toString();
    return str.substring(9, str.indexOf("("));
}

function Foo() {
    this.abc = 123;
}

// will print "Foo"
GetInstanceType(new Foo());
Run Code Online (Sandbox Code Playgroud)

我刚学会了一种从构造函数中提取函数名的简单方法:

obj.constructor.name
Run Code Online (Sandbox Code Playgroud)