【问题标题】:getting the value of static method in javascript class获取javascript类中静态方法的值
【发布时间】:2020-03-17 04:24:59
【问题描述】:

我无法弄清楚如何获取类的静态方法的值。我的代码如下。

class Field {
    constructor(rows = 11, cols = 10) {
    this.numRows = rows
    this.numCols = cols
    }

    static loadFromFileContents(contents) {
        this.numCols = contents.split('x')[0]
        this.numRows = contents.split('x')[1]

    }
}
const contents = `4 x 5`
const field = Field.loadFromFileContents(contents)
console.log(field.numCols)
console.log(field.numRows)

首先,我想获取静态方法的实例。像instanceof(field) 这样的东西,它应该等于'Field'。但我不知道我的语法对于获取实例是否正确。其次,我希望 field.numCols 的返回值应该等于 4,因为第一个拆分值和 field.numRows 应该等于 5。抱歉,我对类的静态方法不太熟悉。我希望你能帮我解决我的问题。非常感谢。

【问题讨论】:

  • 是的,我没注意到。我已经修好了

标签: javascript class static


【解决方案1】:

听起来静态方法需要解析传过来的字符串,并返回一个新的Field实例:

class Field {
  constructor(rows = 11, cols = 10) {
    this.numRows = rows
    this.numCols = cols
  }

  static loadFromFileContents(contents) {
    const [rows, cols] = contents.split(' x ');
    return new Field(rows, cols);
  }
}
const contents = `4 x 5`
const field = Field.loadFromFileContents(contents)
console.log(field.numCols)
console.log(field.numRows)

【讨论】:

  • 哇,谢谢。有效。这个 assert.instanceOf(field, Field) 怎么样?我怎样才能使字段的实例等于字段?
  • 可以使用field instanceof Field,说明解析为true
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
  • 2016-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多