代码之家  ›  专栏  ›  技术社区  ›  mikemaccana

在另一个对象的构造函数中创建新的ES6对象失败

  •  -2
  • mikemaccana  · 技术社区  · 6 年前

    编辑 这个问题不同于 How to extend a class without having to using super in ES6? Person CreationEvent 并不是从对方那里继承的。

    我有两个ES6班, 创造性事件 ( 创造性事件 继承自 Event ). 我想做一个决定 new CreationEvent 当我做一个 new Person (作为 是历史事件的一部分)。

    new CreationEvent() 它自己的作品很好。但是我不能跑 new Person() .

    class Event {
        constructor() {
            this.time = Date.now()
            this.tags = []
        }
    }
    
    class CreationEvent extends Event {
        constructor() {
            this.description = "Created"
        }
    }
    
    class Person {
        constructor(givenName, familyName, email) {
            var creationEvent = new CreationEvent()
        }
    }  
    

    新人() 退货

    如何在另一个对象的构造函数中创建新的ES6对象?

    1 回复  |  直到 6 年前
        1
  •  6
  •   Sjoerd de Wit    5 年前

    你需要打电话 super() CreationEvent Event 类,需要初始化。这样地:

    class CreationEvent extends Event {
        constructor() {
            super();
    
            this.description = "Created"
        }
    }