Does the ES6 Method Definition Shorthand only create one function object?

Viewed 561

With the "old way" of creating classes in JavaScript, you mostly avoid doing something like this:

function Car {
    this.make = "Renault";
    this.model = "Twingo";
    this.name = function () {
        return this.make + this.model;
    };
}

because it would create a new function object at each instantiation of the class, so you'd rather do this:

function Car {
    this.make = "Renault";
    this.model = "Twingo";
}

Car.prototype.name = function() {
    return this.make + this.model;
}

In ES6, and with the newer class syntax we can do something like:

class Car {
    constructor(make, model) {
        this.make = make;
        this.model = model;
    }
    name () {
        return this.make + this.model;
    }
}

Does this only create one shared function object? Or does it instance a new one at each new call like the first one?

1 Answers

Functions that you define as a property inside constructor will be created for each instance. Functions that you define outside constructor will be available on ths prototype. So the name functon will be created only once.

Say this is your class

class Test {
  constructor(prop1, prop2) {
    this.prop1 = prop1;
    this.prop2 = prop2;
    this.func1 = function() {};
  }
  func2() {}
}

const test = new Test('one','two');

If you check in devtools you can see func1 is available for each instance but func2 is available for on the prototype.

Test {prop1: "one", prop2: "two", func1: ƒ}
  func1: ƒ ()
  prop1: "one"
  prop2: "two"
  __proto__:
    constructor: class Test
    func2: ƒ func2()
Related