Reading through 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 the jQuery people pull such a trick?
The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
The optional chaining operator ( ?. ) accesses an object's property or calls a function. If the object is undefined or null , it returns undefined instead of throwing an error.
The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.
John Resig explains this pretty well: http://ejohn.org/apps/learn/#36 and http://ejohn.org/apps/learn/#38
Basically, Event
is a function and an object (functions are objects). The first line of Event checks if it is being called as a function or as an instance of the Event object (with the new operator).
If you are looking for specifically how jQuery does it, 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 explanation for this is on the jQuery forms.
Basically, on lines 3178-3194 the preventDefault event is added to the Event prototype. If the event is instantiated with new
it will be given this preventDefault method. Otherwise, it won't be defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With