gpt4 book ai didi

node.js 简单项目 : ReferenceError: is not defined

转载 作者:行者123 更新时间:2023-12-01 11:24:39 25 4
gpt4 key购买 nike

我尝试学习 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 is not defined at Object. (/Users/tamirscherzer/POC/projects/NodeJS/tutorials/classes/AccountModel.js:5:28) at Module._compile (module.js:397:26) at Object.Module._extensions..js (module.js:404:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Module.require (module.js:353:17) at require (internal/module.js:12:17) at Object. (/Users/tamirscherzer/POC/projects/NodeJS/tutorials/classes/main.js:5:1) at Module._compile (module.js:397:26) at Object.Module._extensions..js (module.js:404:10)



真奇怪,如果我改了 require('./baseModel.js');换成其他名字,我得到错误,找不到文件,所以路径写得正确。

还定义了权限 777 - 同样的事情, BaseModel is not defined
有任何想法吗?

最佳答案

当您在 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;

主.js:
"use strict";

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

let accounts = new AccountModel(5)

accounts.getName()

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

关于node.js 简单项目 : ReferenceError: <ClassName> is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38590002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com