node.js简单项目:ReferenceError:<classname>未定义

时间:2016-07-26 12:31:47

标签: node.js ecmascript-6

我尝试学习Node.js(ES6),但在require

上失败

这是我的结构:

enter image description here

baseModel.js

"use strict";

class BaseModel {
  constructor(options = {}, data = []) { // class constructor
      this.name = 'Base'
      this.url = 'http://azat.co/api'
      this.data = data
      this.options = options
    }

    getName() { // class method
        console.log(`Class name: ${this.name}`)
    }
}

AccountModel.js

"use strict";

require('./baseModel.js');

class AccountModel extends BaseModel {
    constructor(options, data) {

    super({private: true}, ['32113123123', '524214691']) //call the parent method with super
      this.name += 'Account Model'
      this.url +='/accounts/'
    }


    get accountsData() { //calculated attribute getter
    // ... make XHR
        return this.data
    }

}

main.js

"use strict";

require('./AccountModel.js');

let accounts = new AccountModel(5)

accounts.getName()

console.log('Data is %s', accounts.accountsData);

现在我运行:node --harmony-default-parameters main.js

并收到错误:

  

ReferenceError:未定义BaseModel       在对象。 (/Users/tamirscherzer/POC/projects/NodeJS/tutorials/classes/AccountModel.js:5:28)       在Module._compile(module.js:397:26)       at Object.Module._extensions..js(module.js:404:10)       在Module.load(module.js:343:32)       在Function.Module._load(module.js:300:12)       在Module.require(module.js:353:17)       at require(internal / module.js:12:17)       在对象。 (/Users/tamirscherzer/POC/projects/NodeJS/tutorials/classes/main.js:5:1)       在Module._compile(module.js:397:26)       在Object.Module._extensions..js(module.js:404:10)

真的很奇怪,如果我将require('./baseModel.js');更改为其他名称,我会收到错误的文件未找到,因此路径写得正确。

还定义了权限777 - 同样的事情,BaseModel is not defined

任何想法?

1 个答案:

答案 0 :(得分:3)

当您在Node中定义变量时,它不会像在浏览器中那样添加到全局范围中 - 它是该文件/模块的本地变量。因此,您不能简单地导入文件并期望在其中定义的内容可用 - 您必须明确地导出和导入它们。

BaseModel.js:

class BaseModel {
  constructor(options = {}, data = []) { // class constructor
      this.name = 'Base'
      this.url = 'http://azat.co/api'
      this.data = data
      this.options = options
    }

    getName() { // class method
        console.log(`Class name: ${this.name}`)
    }
}

module.exports = BaseModel;

AccountModel.js:

"use strict";

let BaseModel = require('./baseModel.js');

class AccountModel extends BaseModel {
    constructor(options, data) {

    super({private: true}, ['32113123123', '524214691']) //call the parent method with super
      this.name += 'Account Model'
      this.url +='/accounts/'
    }


    get accountsData() { //calculated attribute getter
    // ... make XHR
        return this.data
    }

}

module.exports = AccountModel;

main.js:

"use strict";

let AccountModel = require('./AccountModel.js');

let accounts = new AccountModel(5)

accounts.getName()

console.log('Data is %s', accounts.accountsData);