ES6使用静态方法创建新实例为子类属性提供了未定义的条件

问题描述 投票:0回答:1

我有以下子课程:

export default class File extends Model {
  selected = false
}

和父类:

export default class Model {
  constructor (attributes = {}) {
    if (new.target === Model) {
      throw Error('Not allowed to instantiate Model')
    }

    Object.assign(this, attributes)
  }

  static build (attributes) {
    return new this(attributes)
  }
}

我希望使用时>

const file = File.build({selected: true})

file.selected的结果为true,但为false。在构造函数中记录“ this”,我可以看到File实例根本没有selected属性,返回undefined。

使用当前的babel配置

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current'
        }
      },
      '@babel/preset-typescript'
    ]
  ],
  plugins: [
    '@babel/plugin-transform-typescript',
    '@babel/plugin-proposal-class-properties'
  ]
}

如果我未在子类上定义selected,那么对于file.selected,结果将为true

我有以下子类:导出默认类文件扩展了Model {selected = false}而父类:导出默认类Model {构造函数(attributes = {}){if(new ....

javascript es6-class
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.