2016-06-11 3 views
0

Я пишу небольшую игру линкоров, и я реорганизую свой код с помощью Javascript Objects, инструмента, с которым я не очень хорошо знаком. Я хотел бы иметь возможность вызвать функцию из функции, используя объекты, и я не могу понять, как это сделать. Код здесь:Функции вызова из функций JS

<script> 
var xPos; 
var yPos; 
var boatGrid = { 

    selectPos : function() { 
     console.log("it works"); //want to try calling function addNumber() here 
     for (boatNum = 1; boatNum < 4; boatNum++) { 
      xPos = Math.floor(Math.random() * 8); 
      yPos = Math.floor(Math.random() * 10 + 1); 
     } 
    }, 
    buildBoat : function() { 
     console.log("this works too"); 
     for (boatLen = 1; boatLen < 4; boatLen++) { 
      xPos = xPos++; 
      boatPos = "cell_" + xPos + "_" + yPos; 
     } 
    }, 
    addNumber : function() { 
     document.getElementById("test2").innerHTML = "hello"; //debug line 
    } 
} 

Функция addNum() существует как отлаживать.

+0

Я не могу получить его. Вы имели в виду вызов 'boatGrid.addNumber()'? – Chay22

ответ

0

Вы почти там.

В вашем случае boatGrid является объектом, а addNumber является одним из его методов. поэтому используйте this.addNumber()

var xPos; 
var yPos; 
var boatGrid = { 

    selectPos : function() { 
     console.log("it works"); //want to try calling function addNumber() here 
    this.addNumber(); // Changed here 
    for (boatNum = 1; boatNum < 4; boatNum++) { 
      xPos = Math.floor(Math.random() * 8); 
      yPos = Math.floor(Math.random() * 10 + 1); 
     } 
    }, 
    buildBoat : function() { 
     console.log("this works too"); 
     for (boatLen = 1; boatLen < 4; boatLen++) { 
      xPos = xPos++; 
      boatPos = "cell_" + xPos + "_" + yPos; 
     } 
    }, 
    addNumber : function() { 
     //document.getElementById("test2").innerHTML = "hello"; //debug line 
    document.write('<pre>Add Number called</pre>') 

    } 
} 
boatGrid.selectPos(); 

jsfiddle

0

Если вы хотите вызвать boatGrid.selectPos() и вызвать addNumber функцию внутри функции selectPos, просто добавьте this.addNumber(); в функции selectPos.

selectPos : function() { 
     console.log("it works"); 
     this.addNumber(); // <---- boatGrid calls addNumber() 
     for (boatNum = 1; boatNum < 4; boatNum++) { 
      xPos = Math.floor(Math.random() * 8); 
      yPos = Math.floor(Math.random() * 10 + 1); 
     } 
    } 

При использовании в функции объекта, this относится к объекту вызывающей функции.

Так идти с моим оригинальным, например, boatGrid звонки selectPos, так this в функции selectPos относится к boatGrid.

Таким образом, this.addNumber() будет иметь то, что boatGrid объект вызывает его addNumber функция.

0

Использование

this.addNumber(); 

Ваш код должен выглядеть следующим образом

selectPos : function() { 
    console.log("it works"); 
    this.addNumber(); //want to try calling function addNumber() here 
    for (boatNum = 1; boatNum < 4; boatNum++) { 
     xPos = Math.floor(Math.random() * 8); 
     yPos = Math.floor(Math.random() * 10 + 1); 
    } 
}, 
Смежные вопросы