简体   繁体   English

在node.js中,如何从app.js中的另一个模块中的模块访问函数?

[英]In node.js how do I access a function from app.js that is in a module that is in another module?

I am creating a battleship game to learn node.js. 我正在创建一个战舰游戏来学习node.js。 In the app.js file I create two players based on a module called Users which imports a module called Board. 在app.js文件中,我基于一个名为Users的模块创建了两个播放器,该模块导入了一个名为Board的模块。 Inside the Board module I have a function named placeShip. 在Board模块内部,我有一个名为placeShip的函数。 How can I access this placeShip function from app.js? 如何从app.js访问此placeShip函数? As it is I get a TypeError: Player1.placeShip is not a function. 因为它是一个TypeError:Player1.placeShip不是一个函数。

Users module: 用户模块:

var User = function() {
var board = require('./Board');
return {
    Username: "",
    Gender: "",
    Player: "",
    Turn: "",
    Ships: {
        Carrier: ['C','C','C','C','C'],
        Battleship: ['B','B','B','B'],
        Cruiser: ['Z','Z','Z'],
        Submarine: ['S','S','S'],
        Destroyer: ['D','D']
    },
    Board: new board,
    Hit: function (ship,position) {
        var x = this.Ships[ship][position];
        if(x != null && x != undefined) {
            this.Ships[ship][position] = 'X';
        }
    },
    OutputAll: function () {
        for (var item in this) {
            if (item == "Ships") {
                console.log("Ships: ");
                for (var ship in this.Ships) {
                    console.log("    " + ship + ": " + this.Ships[ship]);
                }
            } else if(item != "Hit" && item != "OutputAll" && item != "Board") {
                console.log(item + ": " + this[item]);
            }
        }
    }
}
}

module.exports = User;

Board module: 主板模块:

var GameBoard = function() {
return {
    Yours: createArray(10),

    Mine: createArray(10),

    ClearBoards: function () {
        this.Yours = createArray(10);
        this.Mine = createArray(10);
    },

    DisplayBoard: function(board){
        for(var i in board){
            console.log(board[i]);
        }
    }
}
}

function createArray(length) {
var table = new Array(length);

for (var i = 0; i < length; i++) {
    table[i] = new Array(length);
    // Make each space a 0
    for (var row = 0; row < length; row++) {
        table[i][row] = 0;
    }
}
return table;
}

function placeShip(ship,rowStart,rowEnd,colStart,colEnd) {
var letter;

//=====Get Ship Letter======
for (x = 0; x < ship.length; x++) {
    if (ship[x] != 'X') {
        letter = ship[x];
        break;
    }
}

//=====Get Orientation=======
// Ship is horizontal
if (rowStart === rowEnd) {
    // Put the ship letter where it lies
    for (x = colStart; x <= colEnd; x++) {
        this.Board.Mine[rowStart][x] = letter;
    }
}
// Or Ship is vertical
else if (colStart === colEnd) {
    // Put the ship letter where it lies
    for (x = rowStart; x <= rowEnd; x++) {
        this.Board.Mine[x][colStart] = letter;
    }
}
// Or Ship is diagonal
else {
    // Put the ship letter where it lies
    this.Board.Mine[rowStart][colStart] = letter;
    for (x = 0; x < ship.length; x++) {
        this.Board.Mine[rowStart + 1][colStart + 1] = letter;
    }
}
}

module.exports = GameBoard;
module.exports.placeShip = placeShip; 

app.js: app.js:

var http = require('http');
var fs = require('fs');
var Users = require('./public/Scripts/Users');

var Player1 = new Users;
var Player2 = new Users;

// When a user navigates to the site
function onRequest(request, response){
console.log("User made a " + request.method + " request from " + request.url);

Player1.Username = "Jamie";
Player1.Hit("Carrier", 4);
console.log("Player 1 Board:========");
Player1.Board.DisplayBoard(Player1.Board.Mine);
Player1.placeShip(Player1.Ships.Carrier,0,4,0,0);
Player1.Board.DisplayBoard(Player1.Board.Mine);


console.log("Player 2 Board:========");
Player2.Username = "Kimyl";
Player2.Board.DisplayBoard(Player2.Board.Yours);
console.log("Player 1: " + Player1.OutputAll());
console.log("Player 2: " + Player2.OutputAll());

// If user asks for the home page
if(request.method == 'GET' && request.url == '/' ) {
    console.log('Successfully requested Home Page');

    // Write a header response
    response.writeHead(200, {"Content-Type": "text/html"});

    fs.createReadStream("./public/index.html").pipe(response);
} else{
    send404Error(response);
}
}

// 404 Error
function send404Error(response){
// Write a header response
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("The page you are looking for could not be found!");
response.end();
}

http.createServer(onRequest).listen(3000);
console.log("Server running...");

We need to use the board module in the User module , so the best way is to pass the board module as a parameter to User and require both in the main file app.js 我们需要在User模块中使用board模块,所以最好的方法是将board模块作为参数传递给User,并且在主文件app.js中都需要

app.js: app.js:

var board = require("./public/scripts/board");
var Users  = require("./public/scripts/Users")(board);

Users module 用户模块

var User = function(board){
  return{
    Board: new board;
  }
}

Move the placeShip function inside of the Board function and change your this.Board.Mine to this.Mine 将placeShip函数移至Board函数内部,并将this.Board.Mine更改为this.Mine

app.js can create a ref to child1 , child2 etc. This ref will allow function calls to child... app.js可以创建对child1,child2等的引用。此引用将允许函数调用child ...

app.js can also 'listen' on events fired in child1, child2 etc. app.js还可以“监听” child1,child2等触发的事件。

  window.addEventListener('child1.event1', function() { $ref.child2.func2(options)}

The transitive call chain is that : 传递调用链是:

child1 can call a function in one of its siblings by fireing an event being listened to by the dispatcher in its parent (app.js) child1可以通过触发其父级(app.js)中的调度程序正在监听的事件来调用其同级函数中的一个。

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

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