Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional `new` operator

Tags:

jquery

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?

like image 341
Randomblue Avatar asked Sep 05 '11 03:09

Randomblue


People also ask

What is the role of new operator?

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.

What is optional chaining operator?

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.

What is new operator in C++?

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.

What is the new operator in Java?

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.


1 Answers

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.

like image 120
Bailey Parker Avatar answered Sep 28 '22 01:09

Bailey Parker