3

I have class

function Foo(a) {
  this.a = a;
  this.bar = function () {
    console.log(this.a);
  };
  this.buz = function () {
    this.a();
    console.log('bzz');
  };
}

and I'll have quite many instances of this class. Should I move methods to prototype?

function Foo(a) {
  this.a = a;
}
Foo.prototype = {
  bar: function () {
    console.log(this.a);
  },
  buz: function () {
    this.a();
    console.log('bzz');
  }
}
Viller
  • 540
  • 5
  • 19

3 Answers3

6

Yes. This will save on memory as each method will be shared instead of recreated each time you instantiate the class.

Methods inside the constructor are considered privileged methods as they can have access to private variables inside the constructor and should only be used if you need access to a private variable.

Crockford on privileged methods

Trevor
  • 11,269
  • 2
  • 33
  • 40
1

Putting class methods is a good idea to save memory. There will be only one instance of the method in the prototype instead of many instances in each object.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
1

The only reason to define methods inside of a constructor in JS is to create a "Privileged" method.

The idea is to create a method that is publicly available, but has access to the private instance variables.

Shad
  • 15,134
  • 2
  • 22
  • 34