Reputation: 20189
I've seen this about a lot recently, even in new programming languages that compile to javascript, where they have replaced typeof
with item.constructor.name
How reliable is this and is there any pros (except the Array type) and cons?
here is an example
var tmp = [];
typeof tmp // object
tmp.constructor.name // Array
Upvotes: 2
Views: 345
Reputation: 27823
Here is a list of cons off the top of my head:
1) Browser support.
It was covered by Felix Kling's answer, non-IE works well. IE - not so much, though i suppose workarounds are possible.
2) Custom constructors
var Foo = function(){};
var foo = new Foo();
console.log(foo.constructor.name); // empty string
Of course, this can be mitigated by enforcing a style where constructors are not allowed to be anonymous functions, or invent a crazy workaround.
var Foo = function Foo(){};
function Bar(){};
var Baz = function (){};
Baz.name = 'Baz';
3) Exceptions
typeof doesn't throw exceptions. Because of this it is used to check if a variable hasn't been defined:
if (typeof baz === 'undefined') console.log('baz not defined');
if (baz === undefined) console.log('Reference error instead!');
Even worse, checking constructor.name throws a TypeError for null and undefined values. This can probably be mitigated by using:
foo != null && foo.constructor.name
4) Wrapper objects.
There are some edge cases where typeof and item.constructor.name return conflicting results:
var foo = false;
var bar = new Boolean(false);
console.log(typeof foo); // boolean
console.log(typeof bar); // object
console.log(foo.constructor.name); // Boolean
console.log(bar.constructor.name); // Boolean
if (foo) console.log('No');
if (bar) console.log('Yes');
There are few scenarios where these actually matter, the above is pretty much the worst case.
5) Speed
I would expect a native operator to be much faster than 2 property checks, though if this idea gets traction it will probably be better optimized as well. Either way, i can't imagine this ever being the bottleneck of your application.
All in all, there are quite a few disadvantages and i can't think of a strong reason to use it.
Upvotes: 1
Reputation: 816364
name
as property of a function is part of the upcoming ES6 standard and currently supported by all browsers expect IE. Aside that, it should be fine to use for built-in objects.
Objects created by user defined constructor functions OTOH might not have the correct constructor
property set, e.g. in cases where inheritance was used but the value of constructor
wasn't set back to the constructor function:
Child.prototype = Object.create(Parent.prototype);
// Child.prototype.constructor = Child;
tl;dr:
Built-in objects and non-IE browsers: reliable
Third party user defined constructor functions or IE: not reliable
Upvotes: 2