Confused by the new operator in JavaScript? Curious about the distinction between a function and a constructor? Or baffled about the purpose of a prototype?
WHAT EXACTLY IS A CONSTRUCTOR?
A constructor is essentially any function that is utilized as a constructor. The language doesn't draw a clear line between them. A function can be designed to serve as a constructor or called like a regular function, giving you flexibility in how it's used.
To utilize a constructor with the new keyword:
var Vehicle = function Vehicle() {
// ...
}
var vehicle = new Vehicle();
WHAT OCCURS WHEN A CONSTRUCTOR IS INITIATED?
When new Vehicle()
is executed, there are four actions performed by JavaScript:
It generates a fresh object.
It assigns the constructor property of the object to Vehicle.
It establishes the object to defer to Vehicle.prototype.
It invokes Vehicle() within the context of the new object.
The resulting output of new Vehicle() is this newly created object.
1. IT GENERATES THE NEW OBJECT.
Simply put, just a brand-new,
new object: {}
.
2. IT ASSIGNS THE CONSTRUCTOR PROPERTY OF THE OBJECT TO VEHICLE.
This implies two things:
vehicle.constructor == Vehicle // true
vehicle instanceof Vehicle // true
It's not just an ordinary property; it won't appear when listing the object's properties. Additionally, attempting to set constructor will only create a normal property on top of this distinguished one. For instance:
vehicle; // {}
var FuzzyBear = function FuzzyBear() { };
vehicle.constructor = FuzzyBear;
vehicle; // { constructor: function FuzzyBear() }
vehicle.constructor == FuzzyBear; // true
vehicle instanceof FuzzyBear // false
vehicle instanceof Vehicle // true
The inherent, internal constructor property is exclusive and cannot be manually configured. It's set automatically during construction utilizing the new
keyword.
3. IT ESTABLISHES THE OBJECT TO DEFER TO VEHICLE.PROTOTYPE.
Here's where it gets intriguing.
A function is simply a unique kind of object, and like any object, it can possess properties. Functions inherently have a property known as prototype, which is initially empty. However, this object undergoes special treatment.
During object creation, it inherits all of the constructor's prototype properties. Admittedly, it's quite a complex concept. Consider this example:
Vehicle.prototype.wheelCount = 4;
var vehicle = new Vehicle;
vehicle.wheelCount; // 4
YOU'VE COVERED A LOT.
The JavaScript prototype chain deviates slightly from conventional practices, making comprehension challenging at first. When syntax merges characteristics resembling other languages, such as borrowing Java's new operator, the learning curve becomes steeper. Nevertheless, with mastery comes the ability to execute some awe-inspiring functionalities.