JavaScript跨模块引用嵌套对象报错:'person未定义'求解答
问题分析与修复方案
核心错误点
属性访问未使用正确的标识符形式
在main.js中,configSettings[person][name]里的person和name会被JS引擎当作变量解析,但你并没有定义这两个变量,因此直接抛出person is not defined错误。正确的属性访问方式有两种:- 点语法(推荐,更直观):
configSettings.person.name - 方括号语法(需用字符串包裹属性名):
configSettings['person']['name']
- 点语法(推荐,更直观):
字符串未加引号
config.settings.js里的color: blue中,blue没有被引号包裹,会被当作变量处理,但你并未定义该变量,运行时会额外抛出blue is not defined错误,需改为'blue'。模块引用路径错误
本地模块引用时,需添加相对路径前缀./,否则Node.js会默认去node_modules目录查找包,导致找不到本地的config.settings.js。
修正后的代码
config.settings.js
var configs = { person: { 'name': 'John', 'number': 27, 'color': 'blue' }, place: { 'town': 'springville', 'population': 201827 } } module.exports = configs;
main.js
var configSettings = require('./config.settings'); module.exports = { run: function(){ console.log(configSettings.person.name); // 或使用方括号语法:console.log(configSettings['person']['name']); } }
内容的提问来源于stack exchange,提问作者boog
相关产品推荐
相关产品推荐

