1

I understand that in Javascript classes don't really exist. An that in reality you're just making a function to construct an object for you.

Not so long ago (before syntactic sugar like "class" was introduced) the only way to mimic a class (and arguably still the best) was as follows :

function Car () {

this.type = "fancy";
this.color = "red";
}

Car.prototype.getInfo = function() {

return this.color + " " + this.type + " car";
};

let car = new Car();

I was wondering how this would look like without "new". Does the following piece of code do exactly the same as the first piece of code?

function Car(self) {

self.type = "fancy";
self.color = "red";
}

Car.prototype.getInfo = function() {

return this.color + " " + this.type + " car";
};

let car = {};
Car(car);
car.__proto__ = Car.prototype;
Jeffrey
  • 73
  • 4
  • 2
    a) you'd use `Object.setPrototypeOf` instead of the deprecated `__proto__` b) you'd set it on the new object *before* calling the constructor c) you'd `call` the constructor so that its `this` keyword refers to the new object, with `Car.call(car)` – Bergi Jun 12 '20 at 20:19
  • Thanks this is where is was looking for :) – Jeffrey Jun 12 '20 at 20:40

2 Answers2

2

I believe they're equivalent. However, you can avoid having to repeat all 3 steps when creating the object by putting those steps in the Car function itself:

function Car() {
  let instance = {}
  instance.type = "fancy";
  instance.color = "red";
  instance.__proto__ = Car.prototype;
  return instance;
}
Car.prototype.getInfo = function() {
  return this.color + " " + this.type + " car";
};

let car = Car();
console.log(car.getInfo());

You can read a summary of what new does in MDN.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

In the first example, car.__proto__.constructor.length == 0. In the second example, it has a value of 1. So depending on how literal you want to be, they may not be equivalent.

I understand that in Javascript classes don't really exist.

syntactic sugar like "class"

Classes are syntactic sugar in every language that supports them. A JavaScript class isn't any less "real" than a C++ class. If anything, it's more real, since it isn't permanently abstracted away to machine code.

Community
  • 1
  • 1
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
  • 1
    Well, I think calling classes "syntactic sugar" in JS makes more sense, cause you can reason about the behaviour of classes if you know how functions and prototypes work. Classes in e.g. C++ introduce "new things" (e.g. destructors) that you cannot replace with other fundamental structures. – Jonas Wilms Jun 12 '20 at 21:07