Additional operator `new`

Reading the jQuery documentation about the event object and its constructor $.Event() I see:

The new operator is optional [when calling the constructor].

That's cool! How did jQuery people get that trick?

+6
source share
2 answers

John Resig explains this pretty well: http://ejohn.org/apps/learn/#36 and http://ejohn.org/apps/learn/#38

In principle, Event is a function and an object (functions are objects). The first line of the event checks whether it is called as a function or as an instance of the Event object (with a new statement).

If you are looking for exactly how jQuery does this, look at line 3134-3138 of the jQuery source:

 jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src, props ); } 

And this is due to jQuery forms .

Basically, on lines 3178-3194, the preventDefault event is added to the prototype Event. If an event is generated using new , it will be given this preventDefault method. Otherwise, it will not be determined.

+7
source

Any custom JavaScript function can be called either with the new operator or with it. Without new it works just like a regular function (because that's what it is). Using new interpreter creates a new object with the corresponding prototype and makes this object the this parameter for calling. This new object is the result of the new operator, unless the return function body is explicitly specified; then the correct value is returned.

So if you write

 function foo() { return { bar: 42 }; } 

you can call it either without or with new - it makes no difference, because the body always explicitly returns a value and never uses this .

+3
source

Source: https://habr.com/ru/post/896614/


All Articles