Javascript NodeJS和ES6类实例中的可变可见性
我正在尝试将一个大型JS代码库从一个文件重构为多个文件中的多个类。我无法访问我认为应该能够访问的变量。我一定对javascript对象/NodeJS模块/exports/imports/引用“this”有些误解 在开始之前,所有内容都在文件ai.js中,位于blockJavascript NodeJS和ES6类实例中的可变可见性,javascript,node.js,ecmascript-6,Javascript,Node.js,Ecmascript 6,我正在尝试将一个大型JS代码库从一个文件重构为多个文件中的多个类。我无法访问我认为应该能够访问的变量。我一定对javascript对象/NodeJS模块/exports/imports/引用“this”有些误解 在开始之前,所有内容都在文件ai.js中,位于blockmodule.exports=function ai(){… 我根据EcmaScript 6类语法创建了文件heatMap.js: module.exports = HeatMap; class HeatMap { cons
module.exports=function ai(){…
我根据EcmaScript 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,...);
...
}
...
}
尝试使用this.ai.currentRound
访问热图内部的currentRound会产生:
未解析的变量currentRound
为什么?“This”应该引用实例化的热图对象“ai”应该引用ai对象,并且ai对象具有变量currentRound。实现此功能的一种方法是将所有变量作为参数在函数调用中传递,但有很多变量,因此这不是一个干净的解决方案。给定
热图定义:
module.exports = HeatMap;
function HeatMap(ai) {
console.log(ai.currentRound);
}
module.exports = AI;
const HeatMap = require('HeatMap');
function AI() {
this.currentRound = 0;
}
AI.prototype.bookKeeping = function bookKeeping() {
const heatMap = new HeatMap(this);
}
以及AI
定义:
module.exports = HeatMap;
function HeatMap(ai) {
console.log(ai.currentRound);
}
module.exports = AI;
const HeatMap = require('HeatMap');
function AI() {
this.currentRound = 0;
}
AI.prototype.bookKeeping = function bookKeeping() {
const heatMap = new HeatMap(this);
}
从AI
的实例调用bookoving()
时,您应该会看到打印的0
我不使用ES2015类,但据我所见,您的作用域是错误的。currentRound
变量的作用域是本地的AI
函数,并且没有以任何方式公开(在您提供的代码段中)因此,当您将AI
的实例传递到HeatMap
中时,currentRound
可用于AI
构造函数公开的方法,但不可用于HeatMap
函数本身。给定HeatMap
定义:
module.exports = HeatMap;
function HeatMap(ai) {
console.log(ai.currentRound);
}
module.exports = AI;
const HeatMap = require('HeatMap');
function AI() {
this.currentRound = 0;
}
AI.prototype.bookKeeping = function bookKeeping() {
const heatMap = new HeatMap(this);
}
以及AI
定义:
module.exports = HeatMap;
function HeatMap(ai) {
console.log(ai.currentRound);
}
module.exports = AI;
const HeatMap = require('HeatMap');
function AI() {
this.currentRound = 0;
}
AI.prototype.bookKeeping = function bookKeeping() {
const heatMap = new HeatMap(this);
}
从AI
的实例调用bookoving()
时,您应该会看到打印的0
我不使用ES2015类,但据我所见,您的作用域是错误的。currentRound
变量的作用域是本地的AI
函数,并且没有以任何方式公开(在您提供的代码段中)。因此,当您将AI
的实例传递到HeatMap
currentRound
时,AI
构造函数公开的方法可用,而HeatMap
函数本身不可用。“AI”应该引用AI对象但是此对象是否有属性currentRound
?您在示例中所做的只是创建一个局部变量currentRound
,而不是一个属性。可能您打算执行this.currentRound=…
?“ai”应该引用ai对象但是这个对象是否有一个属性currentRound
?在您的示例中,您所做的只是创建一个局部变量currentRound
,而不是一个属性。也许您打算这样做this.currentRound=…
?