简体   繁体   English

数组中的Node.js类对象相互影响

[英]Node.js class objects in an array affect each other

When I create an array of classes in JavaScript, editing one affects all other created objects in the array. 当我在JavaScript中创建一个类数组时,编辑一个类会影响数组中所有其他创建的对象。 I'm on node version 8.11.4. 我在节点版本8.11.4上。

I tried using the .push() method to send an update to the array but it still affected every object in the array instead of just the one that was intended. 我尝试使用.push()方法向数组发送更新,但它仍然影响数组中的每个对象,而不仅仅是预期的对象。

This is the class that the objects of the array are. 这是数组对象所在的类。 Tile.js Tile.js

let isObstacle;

class Tile {

    constructor(){
        isObstacle = false;
    }

    setObstacle() {
        isObstacle = true;
    }

    getObstacleStatus() {
        return isObstacle;
    }

}

module.exports = Tile;


This is the second class where the array of Tile objects is. 这是Tile对象数组所在的第二个类。 Test.js Test.js

const Tile = require('./Tile');

let g = [];

//g[0] = new Tile();
//g[1] = new Tile();

g.push(new Tile());
g.push(new Tile());

console.log(g[0].getObstacleStatus());
console.log(g[1].getObstacleStatus());

//g[0].setObstacle();
g.push(g[0].setObstacle());

console.log(g[0].getObstacleStatus());
console.log(g[1].getObstacleStatus());

The expected results are: 预期结果是:

false false 假的

true false 真假

The actual results are: 实际结果如下:

false false 假的

true true 的确如此

The g[0].setObstacle(); g [0] .setObstacle(); is supposed to only set the g[0] instance of isObstacle to true but instead it sets both g[0] and g[1] to true. 应该只将isObstacle的g [0]实例设置为true,而是将g [0]和g [1]都设置为true。

What you are doing is a class that is modifying a global variable called, isObstacle . 你正在做的是一个正在修改名为isObstacle的全局变量的类。 you are declaring that variable outside your class. 你在课堂外声明变量。

just declare isObstacle as an attribute of your class. 只需将isObstacle声明为您班级的属性。

class Tile {
  constructor() {
    this.isObstacle = false;
  }

  setObstacle() {
    this.isObstacle = true;
  }

  getObstacleStatus() {
    return this.isObstacle;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM