Valip
Valip

Reputation: 4610

JavaScript call constructor with parameters from method

I wrote a minimal JavaScript class that accepts 2 parameters for the constructor as follows:

class myClass {
    constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  startProcess() {
    // call other functions that use this.name and this.age
  }
}

var init = new myClass('John', 29);
init.startProcess();

Is there a way to remove the John and 29 parameters when initializing myClass and add them to init.startProcess? I still want those parameters to be accessible from other functions.

Basically, I want to do this and keep the same functionality.

var init = new myClass();
init.startProcess('John', 29);

Upvotes: 0

Views: 67

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68635

Just pass it to the function startProcess and emit them from the constructor. This will let you to initialize the values in two forms. If you don't pass anything to the constructor, it will create variables but set the values to undefined. Also because here is a code duplicating, you can add this part into the private function

class myClass {

  constructor(name, age) {
    this._init(name, age);
  }

  startProcess(name, age) {
    this._init(name, age);
    // Other logics
  }
  
  _init(name, age) {
     this.name = name;
     this.age = age;
  }
}

const init = new myClass();
init.startProcess('John', 29);

console.log(init);

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191916

Remove the constructor and move the initialization code to startProcess:

class myClass {
  startProcess(name, age) {
    this.name = name;
    this.age = age;
  }
}

const init = new myClass();
init.startProcess('John', 29);

console.log(init);

Upvotes: 3

Related Questions