我正在尝试将一个大型JS代码基从一个文件重构为多个文件中的多个类。我无法访问我认为应该能够访问的变量。我一定是误解了javascript对象/ NodeJS模块/导出/导入/引用'this‘的一些东西。
在我开始之前,所有的东西都在ai.js文件中块module.exports = function Ai() { ...中。
我根据6类语法创建了文件heatMap.js:
module.exports = HeatMap;
class HeatMap {
constructor(ai, ...) {
this.ai = ai;
...
}
...
}我修改了ai.js以导入HeatMap类,实例化它,并将对象传递给ai对象的引用,以便heatmap能够访问它的变量。
const HeatMap = require("heatMap.js");
module.exports = function Ai() {
var ai = this;
var currentRound = ...
...
function bookKeeping(...) {
heatMap = new HeatMap(ai,...);
...
}
...
}试图使用currentRound生成的heatMap内部访问this.ai.currentRound:
未解析变量currentRound。
为什么?"This“应该引用实例化的heatMap对象," ai”应该引用ai对象,而ai对象具有变量currentRound。要完成这项工作,一种方法是将所有变量作为函数调用中的参数传递,但是有很多变量,所以它不是一个干净的解决方案。
发布于 2016-03-28 16:40:04
考虑到HeatMap的定义:
module.exports = HeatMap;
function HeatMap(ai) {
console.log(ai.currentRound);
}AI的定义是:
module.exports = AI;
const HeatMap = require('HeatMap');
function AI() {
this.currentRound = 0;
}
AI.prototype.bookKeeping = function bookKeeping() {
const heatMap = new HeatMap(this);
}您应该看到0在从AI实例调用bookKeeping()时打印出来的。
我不使用ES2015类,但据我所见,您的作用域是错误的。currentRound变量的本地作用域为AI函数,并且不以任何方式公开(在您提供的片段中)。因此,当您将AI的实例传递到HeatMap中时,AI构造函数公开的方法可以使用currentRound,而对HeatMap函数本身则不可用。
https://stackoverflow.com/questions/36266467
复制相似问题