簡體   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?

我正在創建一個戰艦游戲來學習node.js。 在app.js文件中,我基於一個名為Users的模塊創建了兩個播放器,該模塊導入了一個名為Board的模塊。 在Board模塊內部,我有一個名為placeShip的函數。 如何從app.js訪問此placeShip函數? 因為它是一個TypeError:Player1.placeShip不是一個函數。

用戶模塊:

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;

主板模塊:

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:

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...");

我們需要在User模塊中使用board模塊,所以最好的方法是將board模塊作為參數傳遞給User,並且在主文件app.js中都需要

app.js:

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

用戶模塊

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

將placeShip函數移至Board函數內部,並將this.Board.Mine更改為this.Mine

app.js可以創建對child1,child2等的引用。此引用將允許函數調用child ...

app.js還可以“監聽” child1,child2等觸發的事件。

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

傳遞調用鏈是:

child1可以通過觸發其父級(app.js)中的調度程序正在監聽的事件來調用其同級函數中的一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM