DEV Community

Discussion on: The keyword "new" in JavaScript

Collapse
 
jordanwuuu profile image
Jordan Wu

If I was to use something similar to your constructor from the first example that doesn't use new, would the output be different in the final example? Could I still use console.log(car2.wner.name)? And what's the advantages of using the new keyword?

Collapse
 
oskargrosser profile image
Oskar Grosser

Using the second method does offer some notable advantages. For example, you can test dynamically if an object is an instance of a certain type/class (see instanceof-operator), or if two objects are of the same type/class (i.e. Object.getPrototypeOf(object1) === Object.getPrototypeOf(object2)).

Another very noteworthy point is the prototype-chain. An object's prototype is like its blueprint.
You can define functions and default values on the prototype, which will then be defined on all instances of this prototype. Assigning a different value on an instance doesn't override it for others, as the newly assigned value is on the instance itself and not on its prototype, overshadowing the prototype's value. This is a resource-friendly way of handling objects, as defaults and functions only need to be instanced once instead of for every instance again.

Also, the ES6 classes have to be instanced using the new keyword. Under the hood, classes are very similar to (if not the same as) constructor functions.

(I hope I didn't say anything wrong here 😅. Anyone correct me if I'm wrong pretty please)