Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I move class methods to prototype? [duplicate]

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');
  }
}
like image 319
Viller Avatar asked Feb 22 '26 12:02

Viller


1 Answers

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

like image 70
Trevor Avatar answered Feb 25 '26 01:02

Trevor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!