2014-11-27 2 views
0

EDIT: Я включил более подробную информацию в функцию getNeighborВ Javascript вы можете вызвать функцию класса внутри другой функции того же класса?

Я знаю, что следующий код длинный, но я суммировал как можно больше. У меня есть следующий код, создающий шестигранную карту:

function Hex (col, row, ter) { //new class of Hexes with row, column, and terrain 
    this.col = col; 
    this.row = row; 
    this.ter = ter; } 

function Map (num_col, num_row) { //create a map of Hexes of dimension num_col x num_row 
    this.num_col = num_col; 
    this.num_row = num_row; 
    this.hexArray = new Array(); 
    for (i=0; i<num_col; i++) {   //creates a 2D array of Hexes with "blank" terrain 
     this.hexArray[i] = new Array(); 
     for (j=0; j<num_row; j++) { 
      this.hexArray[i][j] = new Hex(i, j, "blank"); }} 

    this.step1 = function() { 
    //assigns a terrain value to 30% of the hexes in the map ("seeds" the map) and returns an array called step1Array whose values are the seeded Hexes. 

    this.getNeighbor = function(hex) { //returns all the neighbors of the given hex in an array called neighborArray 
     var delta = [[1, -1, 0], [1, 0, -1], [0, 1, -1], 
       [-1, 1, 0], [-1, 0, 1], [0, -1, 1]]; 
     this.neighborArray = new Array(); 

     for (i=0; i<delta.length; i++) { 
      //get the coordinates of the neighbors and store them as newCol and newRow 
      if (newCol<0 || newRow<0 || newCol>this.num_col-1 || newRow>this.num_row-1 //skip any hexes that are out of bounds 
       || this.hexArray[newCol][newRow].ter !== "blank") continue;    //or that are already seeded 
      this.neighborArray.push(this.hexArray[newCol][newRow]); } 

    return this.neighborArray; 
} 

    this.step2 = function() { //assigns a terrain value to all "blank" neighbors of the seeded hexes 
     for (i=0; i<this.step1Array.length; i++) { 
      this.getNeighbor(this.step1Array[i]); 
      if (this.neighborArray.length === 0) continue; //if there are no "blank" neighbors, continue to the next seeded Hex 
      else { 
       for (j=0; j<this.neighborArray.length; j++) { //else assign each blank neighbor a terrain value 
         var percent = Math.random(); 
         var temp_col = this.neighborArray[i].col; 
         var temp_row = this.neighborArray[i].row; 
       //based on the value of "percent", assign this.hexArray[temp_col][temp_row].ter a given value 
       } 
      } 
     } 
    } 

var testMap = new Map(3,3) //create a 3x3 map of hexes 
testMap.step1();   //seed the map 
testMap.step2();   //assign terrain values to neighbors of seeded hexes. get error. 

Моя проблема заключается в том, что я получаю следующее сообщение об ошибке при компиляции: неперехваченным TypeError: Не удается прочитать свойство «седловины» неопределенной

Я экспериментировал много с функциями step1 и getNeighbor, и они возвращают точные массивы Hexes, поэтому я не думаю, что это проблема.

Я не могу понять, в чем проблема. Есть ли проблема с вызовом функции getNeighbor в функции step2? по какой-то причине не нравится

var temp_col = this.neighborArray[i].col; 
+3

Ясно 'this.neighborArray [я]' не имеет 'col' собственности, но вы не показывает нам, как создается этот массив, или, как он выглядит? – adeneo

+0

Где вы определяете 'this.step1Array'? – Barmar

+0

@adeneo Вы правы - и еще более ясно, это потому, что 'this.neighbourArray [i]' 'undefined'. В логике должна быть ошибка, так что не все ячейки этого массива были заполнены ко времени вызова. (И вот почему мне нравится функциональный подход и избегаю изменчивого состояния, потому что невозможно сказать, кто «должен был» заполнить этот массив ...) –

ответ

1

Это может быть, что ваш «это» не «это» Вы думаете, что это, как вы во внутренней функции.

Вы можете попробовать:

var _this = this; //Create a local variable containing this 
this.step2 = function() { //assigns a terrain value to all "blank" neighbors of the seeded hexes 
    for (i=0; i<this.step1Array.length; i++) { 
     _this.getNeighbor(this.step1Array[i]); //use _this instead of this 
     if (_this.neighborArray.length === 0) continue; 
+1

Он не во внутренней функции, он находится в методе объекта. – Barmar

Смежные вопросы