【问题标题】:Is constructor a static method of a class?构造函数是类的静态方法吗?
【发布时间】:2021-11-08 06:41:19
【问题描述】:

您好,我是 JavaScript 新手。我想知道类构造函数是否是一个特殊的类静态方法。我有这样一个例子:

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

如果类构造函数是一种静态方法,如何修改createWarrior静态方法才能返回战士实例?

【问题讨论】:

  • 可能与您问题的核心无关,但您能否详细说明为什么使用标准 constructor 不符合您的要求?
  • 我没有看到任何真正的用例,但我只是好奇是否有可能?
  • static 方法中,this 指的是类本身,而不是实例。见How does the “this” keyword work?。为什么不static createWarrior(...args){ return new this(...args); }

标签: javascript


【解决方案1】:

假设您可以通过使用static 方法返回类本身的new 实例来实现此目的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多