从函数JS中调用函数

时间:2016-06-11 08:18:50

标签: javascript object

我正在编写一个小型战舰游戏,我正在使用Javascript Objects重构我的代码,这是一个我不太熟悉的工具。我希望能够使用对象从函数内调用函数,我似乎无法弄清楚如何执行此操作。代码在这里:

<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()函数作为调试。

3 个答案:

答案 0 :(得分: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调用selectPosthis函数中的selectPos引用boatGrid

然后this.addNumber()boatGrid个对象调用其addNumber函数。

答案 1 :(得分:0)

使用

small.delete-comment

您的代码应如下所示

this.addNumber();

答案 2 :(得分: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