gpt4 book ai didi

Javascript 对象的 this 范围,_this 未修复

转载 作者:行者123 更新时间:2023-12-02 16:17:41 24 4
gpt4 key购买 nike

您好,我正在尝试用 JavaScript 创建俄罗斯方 block 。我有一个带有名为 data 的变量的 map 对象。当我从对象调用函数时,“this”不再是对象,而是我认为的本地函数。我尝试在对象构造函数中使用声明变量 _this = this 但没有帮助。

function Map(width, height){
var _this = this;
this.data = [];
for(var i = 0; i < width; i++){
var row = [];
for(var n = 0; n < height; n++){
row.push("0");
}
this.data.push(row);
}
}

Map.prototype.add = function(x, y, shape){
for(var i in shape){
for(var n in shape[i]){
_this.data[x+i][y+n] = shape[i][n];
}
}
}

var colMap = new Map(23,30);
var selectedShape = new FallingShape(0, 0, getShapeArray(randomShapeId(), 0));
colMap.add(selectedShape.x, selectedShape.y, selectedShape.shapeArray);

我正在尝试更改数据的值,但由于范围而无法更改,我尝试了“_this”技巧,但不起作用。谁能帮我理解一下吗?

如果您想查看完整代码,这里有一个 codepen 页面的链接。 http://codepen.io/taylorlutjen/pen/OPGwoo?editors=001

最佳答案

在构造函数中创建的 _this 局部变量是 that 函数的局部变量 - 它在其他函数中不可用。

好消息是您并不真正需要它 - 只需在 .add() 函数中使用 this 即可。

构造函数中的局部变量与任何其他函数中的局部变量没有什么不同。它们并不神奇,而且它们绝对不可用于添加到构造函数原型(prototype)中的其他函数。创建 this 值的 _thisthatself 副本的原因是能够创建像回调函数这样需要引用外部上下文对象的东西。您的代码(发布在此处)都不需要它。

关于Javascript 对象的 this 范围,_this 未修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29425837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com