我有一个名为 UrlBuilder 的类,它遍历 .json 文件然后构建 URL。我可以循环遍历数据并打印正确的输出,但是当我尝试将它推送到类构造函数中定义的数组时,我被告知该数组未定义。
这是我的代码:
"use strict";
const DATA = require("../resources/data.json").services;
class UrlBuilder {
constructor() {
this.serviceArr = [];
}
static _iterateAndBuild(current_val, index, array) {
for(let path of current_val.paths) {
let url = current_val.baseURL + Object.values(path);
this.serviceArr.push(url);
}
let recHistUrl = current_val.server + current_val.recordHistoryUrl;
serviceArr.push(recHistUrl);
console.log("Pushing this value to array: " + recHistUrl);
}
buildServiceArr() {
DATA.forEach(UrlBuilder._iterateAndBuild);
}
}
module.exports = UrlBuilder;
如您所见,我将回调函数从 forEach 中分离出来。因此,当我调用 UrlBuilder.buildServiceArr
时,它会循环遍历 DATA 对象并执行上面编写的回调。
这是输出:
C:\Users\payton.juneau\Desktop\Me\Projects\Node\com.etouchmenu.serviceSpyGlass>node app.js C:\Users\payton.juneau\Desktop\Me\Projects\Node\com.etouchmenu.serviceSpyGlass\utilities\urlBuilder.js:13 this.serviceArr.push(url); ^ TypeError: Cannot read property 'serviceArr' of undefined at _iterateAndBuild (C:\Users\payton.juneau\Desktop\Me\Projects\Node\com.etouchmenu.serviceSpyGlass\utilities\urlBuilder.js:13:18) at Array.forEach () at UrlBuilder.buildServiceArr (C:\Users\payton.juneau\Desktop\Me\Projects\Node\com.etouchmenu.serviceSpyGlass\utilities\urlBuilder.js:23:14) at Object. (C:\Users\payton.juneau\Desktop\Me\Projects\Node\com.etouchmenu.serviceSpyGlass\app.js:10:12) at Module._compile (module.js:660:30) at Object.Module._extensions..js (module.js:671:10) at Module.load (module.js:573:32) at tryModuleLoad (module.js:513:12) at Function.Module._load (module.js:505:3) at Function.Module.runMain (module.js:701:10)
提前感谢您的宝贵时间!可能是像范围界定这样愚蠢的事情。
最佳答案
DATA.forEach(UrlBuilder._iterateAndBuild);
应该是
DATA.forEach(UrlBuilder._iterateAndBuild, this);
因此 buildServiceArr
中的 this
作为 _iterateAndBuild
的 this
传递。
作为一般的风格评论,如果你有一个不应该作为静态公开的函数,只需将它放在类之后,例如
class UrlBuilder {
// ...
buildServiceArr() {
DATA.forEach(iterateAndBuild);
}
}
function iterateAndBuild(current_val, index, array) {
// ...
}
虽然对于你的情况我不确定为什么它是静态的而不是实例方法,例如
class UrlBuilder {
// ...
_iterateAndBuild(current_val, index, array) {
// ...
}
buildServiceArr() {
DATA.forEach(this._iterateAndBuild, this);
}
}
这将更符合您的尝试。
关于JavaScript 类 : Member Defined In Constructor Undefined?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48290528/