我有一个对象的构造函数。由于它的创建参数是固定的,我将它们作为数组存储在 JSON 文件中,并希望我能让构造函数从该文件中获取参数。
即使读取 JSON 文件很快,我也不愿意这样做,并且认为我可以这样做:
//test.json:
[
{"foo": "L", "bar": 120000},
{"foo": "T", "bar": 1000},
{"foo": "D", "bar": 1000}
]
现在,在我的对象中,我只需要解析 JSON,并从中创建对象,我认为它会很简单:
//test.js
var fs = require('fs'),
tests = [];
function Test(id) {
this.foo = tests[id].foo;
this.bar = tests[id].bar;
}
function print() {
console.log(this);
}
module.exports = Test;
Test.prototype.print = print;
fs.readFile('./tests.json', function (err, data) {
if (err) {
console.log('Error reading tests.json\n' + err);
throw err;
return ;
}
tests = JSON.parse(data);
});
但是当我尝试使用它时:
var Test = require('./test.js'),
t = new Test(0);
t.print();
Node 在 test.js
中的 tests
上抛出未定义的错误。
我能看到的解决方案都是不切实际的:
- 在构造函数中解析 JSON。它要么阻塞事件循环,要么使构造函数异步,这两种方式都是不好的。
- 从外部解析 JSON,并创建一个简单的类构造函数。这是不切实际的,因为该对象在多个模块中使用,其中一些模块本身就是对象,因此需要将该 JSON 作为参数...
我错过了什么?这种模式是否可行,或者我应该重新开始并寻找另一种解决方案?
最佳答案
它会抛出未定义错误
,因为fs.readFile()
是异步的,因此当您尝试读取它时tests
尚未初始化。
你不需要手动读取 json 文件并解析它,你可以 require 它,你会得到一个很好的对象:
var tests = require('./tests.json'); // << make sure the path is ok
console.log(tests);
关于javascript - 在构造函数内部从 JSON 获取构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34117975/