【问题标题】:Flow javascript class properties get overwritten with undefinedFlow javascript类属性被未定义覆盖
【发布时间】:2018-11-09 21:41:43
【问题描述】:

我有两门课

export class Model {
_id: ID

  constructor(arg : ID | string | Object) {
   if (typeof arg === 'object') this.loadObject
 }


  loadObject(obj: Object) {
    Object.assign(this, obj)
    // using a for loop to assign keys does not work with flow
  }
}

export class User extends Model {
_id: ID
username: string
//...other properties
}

当我调用new Model(userObject) 时,所有属性都已定义。但是当我调用new User(userObject) 时,只有一些属性被定义,一些仍然未定义。为什么会发生这种情况,我该如何解决?

【问题讨论】:

    标签: javascript node.js flowtype


    【解决方案1】:

    您忘记拨打this.loadObject,需要在Userconstructor中拨打super

    试试这个:

    export class Model {
      _id: ID
    
      constructor(arg: ID | string | Object) {
        if (typeof arg === 'object') this.loadObject(arg)
      }
    
      loadObject(obj: Object) {
        Object.assign(this, obj)
      }
    }
    
    export class User extends Model {
      _id: ID
      username: string
    
      constructor(arg) {
        super(arg)
      }
    }
    

    【讨论】:

    • 仍然对我不起作用.. 用户对象在模型构造函数中的 this.loadObject() 之后,但如果在用户构造函数中的 super(arg) 之后记录则错误。
    • 有趣的是,有些属性已初始化,有些则没有(并且不取决于属性的类型)。参数对象来自 JSON,尽管它应该无关紧要..
    • JSON 无关紧要。如果给一个具有所有用户属性的对象仍然显示它们未定义。
    • 那我不知道是什么问题。它对我有用.. 我创建了一个用户(new User({ prop1: 123 }) 并在超级调用后的用户构造函数中记录了:console.log(this.prop1),我看到了123
    • 我在使用 babel 编译之前使用 flow-remove-types 解决了。我认为这是一个@babel/preset-flow 问题。当它看到类属性在构造函数后添加Object.defineProperty
    猜你喜欢
    • 1970-01-01
    • 2017-12-22
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 2012-06-02
    • 2019-07-20
    • 2019-04-03
    相关资源
    最近更新 更多