0

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);

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.