ES6 class setter 不被识别为函数

ES6 class setter is not recognized as a function

我正在尝试使用 getters 和 setters 来调整最初使用 class 构造函数设置的数据。 getter 似乎有效:

class myClass {
  constructor(sth) {
    this.data = {
      sth,
      timestamp: new Date()
    }
  }
  
  create(createData) {
    const newData = Object.assign({}, this.theData, {
    /*      this getter seems to work ^^^^^^^^^^^^ */
      createData
    })
    console.log(newData) // looks good
    // set'ter new data
    this.theData(newData)
    return this
  }
  
  get theData() {
    return this.data
  }
  
  set theData(newData) {
    console.log('setting')
    this.data = newData;
  }
}
         
const Instance = new myClass('construct data')
  .create({createData: 'some data'})

但是这样会报错

zakeyumidu.js:27 Uncaught TypeError: this.theData is not a function

at myClass.create

创建一个非setter方法似乎可以正常工作

setTheData(newData) {
  this.data = newData // yep, that works
}

但我认为 getters/setters 是首选。

像我的示例那样在 class 方法中设置这样的实例数据可以吗?如果不是,为什么我的 setter 不工作?

而不是 this.theData(newData) 你应该写 this.theData = newData

class myClass {
  constructor(sth) {
    this.data = {
      sth,
      timestamp: new Date()
    }
  }

  create(createData) {
    const newData = Object.assign({}, this.theData, {
    /*      this getter seems to work ^^^^^^^^^^^^ */
      createData
    })
    console.log(newData) // looks good
    // set'ter new data
    this.theData = newData;
    return this
  }

  get theData() {
    return this.data
  }

  set theData(newData) {
    console.log('setting')
    this.data = newData;
  }
}

const Instance = new myClass('construct data')
  .create({createData: 'some data'})

this.theData(newData) 将访问 theDatagetter。由于 .data 在该行执行时(或永远不会)不是函数,这就是您收到该错误的原因。

要解决这个问题,您实际上应该使用 setter:

this.theData = newData;