Question

I have a custom object that takes a jQuery object as an argument. What is the best way to handle stopping the instantiation of the object if an invalid datatype is passed.

var MyObj = function( $obj ) {

    if( ! ($obj instanceof jQuery) )
        return false // This is where it should cancel or error or something

}

var myInstance = new MyObj( 'invalid' );
Was it helpful?

Solution

I guess the best way to tell the user that something is wrong is to throw a new error like that :

throw new Error('Wrong object type');

But it really depend on your goal.

Example, jQuery doesn't trow an error when you pass invalid argument to his constructor, it just return an empty object and the code continue.


After seeing Cal Markham answer, i am a little bit confused about your question.

If your are looking why your code doesn't work, just comment and ill delete that answer since it does answer your current question.

OTHER TIPS

The best way to handle an exceptional situation depends on the particular circumstances of your code. In some cases, when you have the option, you can continue execution in a non-surprising way. In others, when you can't return a meaningful object, you should throw an error. The best guideline is that your code shouldn't surprise the person using it.

An example of an exceptional situation handled in a non-surprising way is in jQuery:

$('#myDiv').css('color', 'red');

Suppose that there is no #myDiv, you could throw an error to alert the developer that he's trying to change the color of an inexisting element. Or you could silently ignore it. jQuery chose the second option and made it work in a coherent, non-surprising way.

The advantage of throwing errors sooner is that the developer needs less time debugging when something goes wrong. The disadvantage is that the code will probably be messier.

The code you have would work fine, just a little syntax error for instanceof. It should be

if( ! ($obj instanceof jQuery) )

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top