【问题标题】:How can I instantantiate an object of a class created in other file?如何实例化在其他文件中创建的类的对象?
【发布时间】:2019-09-24 13:26:35
【问题描述】:

您好,我是 javascript 新手,我无法实例化另一个类的对象,我用一个简单的示例对其进行了总结。当我运行 foo.js 时出现以下错误:

let j = new Test(3) TypeError: Test is not a constructor

Test.js:

class Test{
    constructor(k){
        this.myAttribute = k
    }
    print(){
        console.log("This is my attribute " + k)
    }
}

Foo.js:

'use strict'

const Test = require('./test.js')

let j = new Test(3)
j.print()

我做错了什么?这很简单,我不知道我做错了什么。

【问题讨论】:

  • 那是 NodeJS 吗?如果是,请将module.exports = Test; 添加到第一个文件中。

标签: javascript constructor instantiation


【解决方案1】:
export class Test{
    constructor(k){
        this.myAttribute = k
    }
    print(){
        console.log("This is my attribute " + k)
    }
}

然后

import { Test } from './test'

let j = new Test(3)
j.print()

这是一个 StackBlitz 演示 https://stackblitz.com/edit/js-wvrdlj?file=index.js

必须修改您的测试类以记录 myAttribute,因为 k 在 print 方法中未定义

【讨论】:

  • 打印应该使用this.myAttribute
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-08
  • 2011-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多