Hello I am trying to create Tetris in JavaScript. I have map object with a variable called data. When I'm calling a function from the object, the 'this' is no longer the object but the local function I think. I have tried using declaring a variable _this = this in the objects constructor but doesn't help.
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);
I'm trying to change the values of data but can't because of the scope, I've tried the '_this' trick but doesn't work. Can anyone help me understand?
Heres a link to a codepen page if you want to see the whole code. http://codepen.io/taylorlutjen/pen/OPGwoo?editors=001
_thisbefore you run the function and you should be set. I can't tell if this is working with your Codepen example though, so I'll keep this as a comment._thisthat belongs tofunction Map- it won't be accessible anywhere else outside of that function. Pointy explained it better than I did though.