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:

  1. make method public, set() , place() if that, it's callable this.methodplace(0) , know this.
  2. use .call() inject context if that, it's callable methodplace.call(this, 0) , know this.

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:

  1. copy this self , use internally don't this, because there'll self , this floating around, copy class/object this self , use self instead of this in private method (where this has changed):
    (this panta82's solution, using self instead of that, illustrates dislike)

.

var coordinatelist = []; var self = this; function methodplace(indexofmethodtouse) {   // ... //       if (self.cells[rndx+i][rndy] == self.default) {   // <===== 

Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -