Javascript type of custom object

前端 未结 5 1491
春和景丽
春和景丽 2020-12-13 08:28

How can I check if my javascript object is of a certain type.

var SomeObject = function() { }
var s1 = new SomeObject();

In the case above

5条回答
  •  臣服心动
    2020-12-13 08:55

    Whatever you do, avoid obj.constructor.name or any string version of the constructor. That works great until you uglify/minify your code, then it all breaks since the constructor gets renamed to something obscure (ex: 'n') and your code will still do this and never match:

    // 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') {}
    

    Note:

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

    (BTW, I need higher reputation to comment on the other worthy answers here)

提交回复
热议问题