Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do methods take up space in the class instance on javascript?

Similar questions for other languages.

Consider a simple class:

class Foo {
  a;

  constructor(value) {
    this.a = value;
  }

  bar() {
    console.log(this.a);
  }
}

For each instance of this class, in javascript, will be consumed memory for a reference for bar method?

If I add other methods in Foo class, the instance of it will be heavier on memory?

If I need to create a lot of Foo objects, should I write:

function Foo(value) {
  this.a = value;
}

function bar(fooInstance) {
  console.log(fooInstance.a);
}

The questions above only illustrate the same question:
Do methods take up space in the class instance?

like image 754
Jonny Piazzi Avatar asked Aug 08 '26 00:08

Jonny Piazzi


2 Answers

Class methods are properties of the class prototype object, not each instance. Each instance just has a reference to its prototype, and the prototype has a reference to its parent class prototype, and so on.

Properties are found by searching the prototype chain; this is how inheritance works in JavaScript.

like image 109
Barmar Avatar answered Aug 09 '26 14:08

Barmar


Your code:

class Foo {
  a;

  constructor(value) {
    this.a = value;
  }

  bar() {
    console.log(this.a);
  }
}

Is equivalent to:

function Foo(value) {
  this.a = value;
}

Foo.prototype.bar = function () {
  console.log(this.a);
}

let foo1 = new Foo('foo1');
let foo2 = new Foo('foo2');

foo1.bar();
foo2.bar();

// true only if foo1.bar and foo2.bar reference the same object
console.log(foo1.bar === foo2.bar);

So there is only one bar method on the constructor's public prototype. It's "inherited" by instances of Foo via their private [[Prototype]] property that points to Foo.prototype.

like image 20
RobG Avatar answered Aug 09 '26 12:08

RobG



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!