If I make several instances of a class in Javascript, does each function of each instance get its own space in memory like a variable would?

Viewed 427

I want to make several instances of a class, if I do this, will each instance get its own individual copy of each function in the class, or does each instance just point to a singular copy of the functions in the class? I've tried googling this and found some threads that said most languages don't, but I did find one thread that had people in the comments say this is possible in js, but didn't specify on what conditions. Also, I am using this format to make classes if that helps:

class thing {

  constructor(){

  }

  someFunction(){

  }

}
2 Answers

Try it out. Knowing the === operator is strict equality:

class thing {
  someFunction(){
    return this.meep;
  }
}
const t1 = new thing();
const t2 = new thing();
console.log(t1.someFunction === t2.someFunction);
console.log(t1.someFunction === thing.prototype.someFunction);

In fact, from the second true you can also tell it's the same function as on thing's prototype.

In Object-Oriented Programming, the class you created serves as a blueprint for all the instances (objects) created from that class. This means all the objects inherit the properties and functions(methods) defined in the class.

However, if an instance of a class overrides a class method by defining its own instance method, then the method defined in the class will be ignored during execution. In Javascript, this is achieved through prototype chain.

Read the details here https://javascript.info/prototype-inheritance and here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

Related