【问题标题】:Pass arguments to the class constructor after import导入后将参数传递给类构造函数
【发布时间】:2020-01-17 08:18:45
【问题描述】:

这是我的 parent.class.js

class ParentClass {
    constructor() {
    }
}

module.exports = { ParentClass };

child.class.js

const { ParentClass } = require('./parent.class');

class ChildClass extends ParentClass {
    constructor(index) {
        super();
        this.index = index;
    }

    showIndex() {
        console.log(this.index)
    }
}

module.exports = { ChildClass };

index.js 我正在使用子类的地方

const ChildClass = require('./child.class');

ChildClass(1).showIndex(); // This obviously is not working 

注意:这只是一个例子。在实际项目中我无法使用 ES6 模块导入

我的问题是如何将参数传递给我的 index.js 中的子类实例?

如果是 ES6,我可以这样做:

import ChildClass  from './child.class.js'

const ChildClass = new ChildClass(1)

ChildClass.showIndex(); // outputs 1 ...I guess??


如何将参数传递给子类?

【问题讨论】:

    标签: javascript es6-class


    【解决方案1】:

    问题是

    module.exports = { ChildClass };
    

    const ChildClass = require('./child.class');
    

    您正在导出一个 object,它的属性为 ChildClass,然后您正在导入 整个对象 并尝试调用它。但是对象是不可调用的;你指的不是ChildClass 类。

    就像你解构 ParentClass 一样

    const { ParentClass } = require('./parent.class');
    

    要么解构ChildClass

    const { ChildClass } = require('./child.class');
    

    或者将ChildClass分配给module.exports

    module.exports = ChildClass;
    

    然后您将能够创建ChildClass 的实例并调用实例上的方法:

    const child = new ChildClass(1);
    child.showIndex();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 2014-12-25
      • 1970-01-01
      相关资源
      最近更新 更多