Reputation: 3
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
Upvotes: 0
Views: 139
Reputation: 413757
Your _this
local variable created in your constructor function is local to that function — it won't be available in the other function.
The good news is that you won't really need it - just use this
in that .add()
function.
Local variables in constructor functions are no different than local variables in any other function. They're not magic, and they definitely won't be available to other functions added to the constructor's prototype. The reason for creating a _this
or that
or self
copy of the value of this
is to be able to create things like callback functions that need a reference to the outer context object. None of your code (posted here) needs that.
Upvotes: 2