Is the packaging new in the designer good or bad?

I watched John Resig Best Practices in JavaScript Library Design ; one slide suggested setting up the constructor of the object so that it would instantiate itself.

function jQuery(str, con) { if (window === this) { return new jQuery(str, con); } // ... } 

In this case, new jQuery("#foo") becomes jQuery("#foo") .

I thought this was pretty interesting, but I did not write such a constructor in my own code.

A little later I read the post here about SO. (Sorry, I donโ€™t remember which link I will put. I will update the question if I can find it again.) One of the comments said that it was bad practice to hide new from such a programmer, but did not go into details.

My question is that the above is usually considered good, bad or indifferent, and why?

+6
javascript
source share
3 answers

This is a protective method when people forget to use the new operator before a class function.
The logic is that if a function is called without new , then the global region will still be the current region (instead of new instances), and therefore we simply call the same function using the new operator.

But if you ask me, the right thing is to throw a mistake and actually let the developer know that she made a mistake instead of just โ€œacceptingโ€ it.

But hey, I think this is according to the jQuery mantra:
"instead of allowing users to write quality code, enable / force them to write illogical and invalid code."

+5
source share

IMO I believe that this is a practical and fully operational protective technique.

If you create a constructor constructor , be sure you want to use the newly created instance of the object ( this ) and nothing good will happen if this points to a global object.

Fortunately in the future, in ECMAScript 5 Edition in strict mode, this will simply contain undefined when a function is called without a base object or the new operator ...

See also:

  • Is JavaScript a โ€œnewโ€ keyword considered harmful?
+4
source share

You are returning an object from a function. I do not see any problems in this.

This is the same as doing:

 function getObject(){ return new SomeObject; } 

The only difference is that you are actually returning. But, in fact, this does not seem wrong if you clearly document it. People who are used to jQuery are likely to praise you for improving usability.

+1
source share

All Articles