In javascript 创建新对象时,其中的数组属性 没有初始化为新对象

In javascript when creating a new object, the array property in it does not initializes as a new one

我正在使用 for 循环创建 5 个 "RoundDiv" 类型的新对象,它有一个 属性 "weirdArray",这是一个空数组。在调用 "init()" 方法时。 "someValue" 被推入 "weirdArray".

问题是每次创建 "RounDiv" 类型的新对象时 "someValue" 仅被推送一次,但在单击任何 "roundDiv" 时,控制台日志显示数组中有 5 个元素,而应该只有一个。

    "use strict";

    var roundDivPrototype = {
      weirdArray: new Array(),
      init: function(label) {
        this.weirdArray.push("someValue");
        var me = this;
        var body = document.body;
        var div = document.createElement("div");
        div.className = "roundDiv";
        div.innerText = label;
        div.addEventListener("click", function(e) {
          alert("Length of array: " + me.weirdArray.length);
          console.log(me.weirdArray); //me=this
        });

        body.appendChild(div);
      }
    };
    var RoundDiv = function(label) {
      this.init(label);
    };
    RoundDiv.prototype = roundDivPrototype;

    for (var i = 0; i < 5; i++) {
      new RoundDiv(i);
    }
body {
  background-color: teal;
  text-align: center;
  width: 100%;
}
.roundDiv {
  display: inline-block;
  height: 100px;
  width: 100px;
  background-color: whitesmoke;
  margin: 10px;
  border: solid;
  border-radius: 50%;
  text-align: center;
  font-size: 5em;
  box-sizing: border-box;
  cursor: pointer;
  line-height: 100px;
}
<body>
  <script src="js/main.js"></script>
</body>

我想出了一个可能的解决方案:

"use strict";

var roundDivPrototype = {
  weirdArray: undefined,
  init: function(label) {
    this.weirdArray = new Array();  //Change in code above
    this.weirdArray.push("someValue");  //Change in code above

    var me = this;
    var body = document.body;
    var div = document.createElement("div");
    div.className = "roundDiv";
    div.innerText = label;
    div.addEventListener("click", function(e) {
      alert("Length of array: " + me.weirdArray.length); //me=this
      console.log(me.weirdArray); //me=this
    });

    body.appendChild(div);
  }
};
var RoundDiv = function(label) {
  this.init(label);
};
RoundDiv.prototype = roundDivPrototype;

for (var i = 0; i < 5; i++) {
  new RoundDiv(i);
}
body {
  background-color: teal;
  text-align: center;
  width: 100%;
}
.roundDiv {
  display: inline-block;
  height: 100px;
  width: 100px;
  background-color: whitesmoke;
  margin: 10px;
  border: solid;
  border-radius: 50%;
  text-align: center;
  font-size: 5em;
  box-sizing: border-box;
  cursor: pointer;
  line-height: 100px;
}
<body>
  <script src="js/main.js"></script>
</body>

虽然我想出了一个可能的解决方案,但仍然想知道为什么在创建 "RoundDiv" 类型的新对象时 "weirdArray" 中的先前值存在...

非常感谢您的贡献:)

在您的第一个示例中,您在对象原型中实例化 weirdArray,使此数组 属性 成为静态的。因此,您的每个 RoundDiv 对象将共享同一个数组来存储您的数据。

像在第二个示例中那样在 init 函数中实例化它可以解决问题。每次创建新的 RoundDiv.

时,都会创建一个 weirdArray 的新实例

请参阅 this fiddle,其中显示了每个示例创建新数组的次数、时间以及每个 push 之后的数组大小。