1

我正在创建类坐标的 4 个实例。接下来,我将通过 setter 更改其中一个值。

class Coordinates {
    constructor(lat, lng) {
        this._lat = lat;
        this._lng = lng;
    }
    get lat() { return this._lat; }
    get lng() { return this._lng; }
    set lat(newLat) { this._lat = newLat; }
    set lng(newLng) { this._lng = newLng; }
}

let points = [];
for (let p = 0; p < 4; p++) {
    const point = new Coordinates(p, p);
    points.push(point);
}
console.log(points);  // Shows the 55, although the setter wasn't executed
points[1].lat = 55;
console.log(points); // Shows the 55 (as expected)

第一个 console.log 显示 0/0、55/1、2/2、3/3。我实际上预期的是 0/0、1/1、2/2、3/3,因为我没有执行 setter。正如预期的那样,第二条日志显示 0/0、55/1、2/2、3/3。有人可以帮我理解吗?

4

1 回答 1

0

由于我无法在 Node.js 中重现,但可以在 Chrome 控制台中重现,我想这是因为该points变量在控制台中延迟显示,即当您单击它以查看详细元素时,它会进行实时重新评估。如果你尝试这个,你会发现问题已经消失,因为现在你有字符串原语而不是活动对象。

console.log(JSON.stringify(points));
points[1].lat = 55;
console.log(JSON.stringify(points));
于 2020-05-31T19:14:05.867 回答