0

'A class constructor encapsulates all properties and methods. However, methods can also be defined outside the constructor in a class.' What is the difference between defining a method inside the constructor or outside the constructor, if both will be on the prototype anyway, and both are within the same class? For example, displayName and getAge

Ex:

class employee{
 constructor(name,age){
  this.name= name
  this.age= age
  this.displayName = function() {
    console.log("Name is:", this.name)
  }
 }
 getAge(){
  return this.age
 }
}
Adri
  • 1
  • 2
  • 1
    _“Both would be defined on the prototype I assume”_ — It depends on whether you do `this.method = function(){`…`}` or `this.constructor.prototype.method = function(){`…`}`. Adding `this.method` would directly affect the instance, not the prototype. _“whether they can be defined inside the constructor as well”_ — Yes, but this creates a new method in memory every time you construct an object, so it’s much less memory-efficient. Methods on the prototype get only created once. See [Ownership of properties](//developer.mozilla.org/en/docs/Web/JavaScript/Enumerability_and_ownership_of_properties). – Sebastian Simon Feb 18 '23 at 17:33
  • Yeah, so a new `displayName` function would be created every time you construct an `employee` — pretty wasteful. A `getAge` method, however, only gets created once, no matter how many `employee`s you construct — that’s the correct, memory-efficient approach. In practical terms, you’ll rarely encounter a difference between these cases. – Sebastian Simon Feb 19 '23 at 00:12

0 Answers0