One case where the constructor property is handy (or would be if it was reliable) is where a function needs to know the type of argument it has been passed, e.g.
function foo(arg) {
if ( /* if arg is an array */ ) {
// deal with array
} else if ( /* if arg is an object */ ) {
// deal with object
}
}
If the above function is passed an array or object, then typeof
will return object in both cases. The constructor property can be used:
if ( arg.constructor == Array )
But that fails if the array is created in a different frame to where the test is taking place (i.e. it's Array constructor is a different object to the Array function in the scope of the test).
So if you rule out frames (or other cases where scope is an issue), then the constructor property is fine to use for this.
But that does not fix the general issue of the constructor property being writable (and therefore can be set to anything) and cases where the prototype chain is more than trivial.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…