0

I am trying to get to know OOP in JS and while trying out the basic constructor functions like this:

const SomeConstructor = function(arg) {
  this.arg = arg
}


SomeConstructor.prototype.method = function()
{
  console.log(`This is a function that is inherited, the argument passed in was: ${this.arg}`)

}


const someObject = new SomeConstructor(1)
someObject.method() 

//Creates class, adds a method to prototype than creates object that inherites it

I wondered if it wouldn't be easier to just put the method declaration into the constructor, so the constructor would look like this:

const SomeConstructor = function(arg) {
  this.arg = arg

  SomeConstructor.prototype.method = function()
  {
  console.log(`This is a function that is inherited, the argument passed in was ${this.arg}`)
  }
}

The object based on this class still kept the same structure - the method was under proto. So what's the catch? Can it be left like this or does it have some performance implications?

  • 2
    You should probably look into ES6/ES2015 classes: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes – Rudie Apr 11 '21 at 14:42
  • You can call it like that but not inside the constructor. You have to call it from outside the constructor if you want to declare it that way. – JΛYDΞV Apr 11 '21 at 14:43
  • If you are going to declare it in the constructor, you want to use this.fooMethod = () => {} – JΛYDΞV Apr 11 '21 at 14:44
  • 1
    It should NOT be inside the constructor. Every time you create an instance using the `new` operator, the `prototype.method` will be overwritten. – adiga Apr 11 '21 at 14:54

0 Answers0