Variable scope incorrectly set-up in Node.JS -
the following mcve of try @ battleship in nodejs. grid.set calls grid.place calls grid.place.methodplace tries call grid.cells , fails. not way access such variable, since this.cells not in scope. correct way of accessing variable?
i'm making mess of it. beginners that.
"use strict"; function grid(x, y) { var r, c, row; this.cells = []; this.default = " "; for(r = 0 ; r < x ; r++) { row = []; for(c = 0 ; c < y ; c++) { row.push(" "); } this.cells.push(row); } } grid.prototype.place = function(length) { function getrandomint(min, max) { return math.floor(math.random() * (max - min)) + min; }; var coordinatelist = []; function methodplace(indexofmethodtouse) { if (indexofmethodtouse == 0) { var rndx = getrandomint(0,(9-length)); var rndy = getrandomint(0,9) for(var = 0 ; <= rndx + length ; i++) { if (this.cells[rndx+i][rndy] == this.default) { // <===== coordinatelist.push(rndx+i,rndy); } }; } console.log(coordinatelist); return coordinatelist; } methodplace(0); }; grid.prototype.set = function(ac) { for(var = 0 ; <= ac ; i++) { this.place(2); } } var friendlygrid = new grid(10,10); friendlygrid.set(1,2,1,1);
at least 2 solutions:
- make method public,
set(),place()if that, it's callablethis.methodplace(0), knowthis. - use
.call()inject context if that, it's callablemethodplace.call(this, 0), knowthis.
if there's no reason have method private, i'd make public: more readable, cleaner, better debuggable, simpler syntax etc. if there reason private (access), i'd use .call()
there's solution:
- copy
thisself, use internally don't this, because there'llself,thisfloating around, copy class/objectthisself, useselfinstead ofthisin private method (wherethishas changed):
(this panta82's solution, usingselfinstead ofthat, illustrates dislike)
.
var coordinatelist = []; var self = this; function methodplace(indexofmethodtouse) { // ... // if (self.cells[rndx+i][rndy] == self.default) { // <=====
Comments
Post a Comment