'Question about the use of 'new' operator in Javascript [duplicate]
From Mozilla documentation I learn about the new operator through this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const car1 = new Car('Eagle', 'Talon TSi', 1993);
console.log(car1.make);
// expected output: "Eagle"
But I also can do this without using 'this' and 'new' operator by doing:
var Car = (make, model, year) => ({make, model, year})
var car1 = Car('Eagle', 'Talon TSi', 1993)
console.log(car1.make)
If I can accomplish the same result without using 'this' and 'new' operator, then what's the point of using them in the first place? Or do I missed something important? Thanks. I'm sorry for the noob question.
Solution 1:[1]
You have the same doubt that most beginners have, the class declaration by function and instantiation, and a function returning an object are very different.
function ClassName(params) {
this.params = params;
}
This creates a class with the name ClassName
and saying new ClassName
returns an instance of the class ClassName
, but the other thing you wrote is:
var ClassName = (params) => ({params: params});
What this means is that it creates a function and sets its return value to the object containing the params.
Pros and Cons:
1st method:
Pros: You can easily see that an object is an instance of another object(particularly, a class) by just saying ClassInstance instanceof CLassName
, in your case, car1 instanceof Car
which returns a boolean
Cons: (Till now, I didn't get any Cons with this method, if you have any Cons with this method, please comment, and I would take them under consideration)
2nd method:
Pros: Each created Object is of its own and does not have a relationship with same looking other object created by the same function (I don't know, how this would be helpful, but in some cases, it might be helpful)
Cons: You can't check that the object is the same(or instance of the same parent) by using ClassInstance instanceof Class
, it would simply return false, and also it would not create an instance, it would just create an object
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Zayaan |