繁体   English   中英

ES6 使用 static 方法创建新实例为子 class 属性提供未定义

[英]ES6 using static method to create new instance gives undefined for child class attributes

我有以下孩子 class:

export default class File extends Model {
  selected = false
}

和父 class:

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 的结果会是真的,但仍然是假的。 在构造函数中记录“this”,我可以看到 File 实例根本没有 selected 属性,返回未定义。

使用当前的 babel 配置

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

如果我没有在子 class 上定义 selected,则 file.selected 的结果将为 true

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields

公共实例字段与Object.defineProperty一起添加,或者在基础 class 中的构造时(在构造函数主体运行之前),或者在super()在子类中返回之后。

this.selected没有及时设置让父构造函数看到它(当你被允许在构造函数中使用this时匹配)。 一种替代方法是将初始值放在原型上:

File.prototype.selected = false;

您可以将Object.assign移动到build方法而不是构造函数吗?

例子:

 class Model { constructor () { if (new.target === Model) { throw Error('Not allowed to instantiate Model') } } static build (attributes) { const obj = new this(attributes) Object.assign(obj, attributes) return obj } } class File extends Model { constructor() { super() this.selected = false this.defaultValue = 'default' } } const file = File.build({selected: true, foo: 'bar'}) console.log(file);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM