繁体   English   中英

从函数JS内调用函数

[英]Calling functions from within functions JS

我正在编写一个小型战舰游戏,并且正在使用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()函数在那里作为调试。

如果要调用boatGrid.selectPos()并在selectPos函数内调用addNumber函数,只需添加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 ,因此selectPos函数中的thisboatGrid

因此, this.addNumber()将使该boatGrid对象调用其addNumber函数。

采用

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);
    }
},

你快到了。

在您的情况下, 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM