问题描述:

Is there a way to detect whether invoking a constructor will result in a TypeError without resorting to a try-catch?

I'm trying to avoid try-catch since it has a huge performance hit.


Context: I'm building a clone() function. In jQuery, for instance, an object's constructor is ignored, resulting in this:

function Panda(){}

var p1 = new Panda(),

p2;

p2 = jQuery.extend(true, {}, (p1)); // cloning

// > Object {}

p2 instanceof Panda;

// > false

At some point, I would like to use this statement in my clone() function, so that I can borrow the constructor to create a new instance:

function clone(obj) {

...

var doppelgangerObj = new obj.constructor();

...

}

p2 = clone(p1);

p2 instanceof Panda;

// > true

I've filtered out Arrays and Array-Like objects (NodeLists, Arguments) already, but illegal constructors errors can happen when you pass in un-constructable browser objects like Console or window.navigator.

Hence, is there a way to detect whether invoking a constructor will result in a TypeError without resorting to a try-catch?

相关阅读:
Top