0

Hi I am new in JavaScript. I am wondering if the class constructor is a special class static method. I have such an example:

class warrior {
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
  sayHello() {
    return `Hello my name is ${this.fullName}`;
  }
  static createWarrior(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    return this;
  }
}

let warrior1 = new warrior("Ashley", "Yuna", 25);
warrior1.sayHello();
let warrior2 = warrior.createWarrior("Kris", "Snow", 23);
warrior2.sayHello();

If class constructor is a kind of static method, how can I modify createWarrior static method to be able to return warrior instance?

yurukyuruk
  • 65
  • 6
  • Maybe tangential to the core of your question, but can you elaborate a bit on why using a standard `constructor` doesn’t meet your requirements? – esqew Sep 12 '21 at 19:56
  • I don't see any real use case but I am only curious if it is ever possible? – yurukyuruk Sep 12 '21 at 19:58
  • 4
    In `static` methods, `this` refers to the class itself, not to the instance. See [How does the “this” keyword work?](/q/3127429/4642212). Why not `static createWarrior(...args){ return new this(...args); }`? – Sebastian Simon Sep 12 '21 at 20:04

1 Answers1

3

You can accomplish this by using the static method to return a new instance of the class itself:

class warrior {
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
  sayHello() {
    return `Hello my name is ${this.fullName}`;
  }
  static createWarrior(firstName, lastName, age) {
    return new this(firstName, lastName, age);
  }
}

let warrior1 = new warrior("Ashley", "Yuna", 25);
console.log(warrior1.sayHello());
let warrior2 = warrior.createWarrior("Kris", "Snow", 23);
console.log(warrior2.sayHello());
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
esqew
  • 42,425
  • 27
  • 92
  • 132