【问题标题】: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 访问函数?
【发布时间】:2015-12-30 02:19:25
【问题描述】:

我正在创建一个战舰游戏来学习 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...");

【问题讨论】:

  • 不确定,但尝试将 './board' 替换为 'board.js'
  • 我可以访问板子模块,因为我可以执行 Player1.Board.DisplayBoard,它会向我显示板子。一旦我添加了 placeShip 函数,它就不行了。
  • 尝试在主 js 文件中要求 board 模块。
  • 但是如果我调用 placeShip,这个调用者将不是玩家,所以它不会更新玩家的棋盘。
  • 在游戏板中也包含 placeShip 作为函数返回并删除 exports.exports.placeship

标签: javascript node.js


【解决方案1】:

我们需要在 User 模块中使用 board 模块,所以最好的方法是将 board 模块作为参数传递给 User 并在主文件 app.js 中同时 require 两者

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

【讨论】:

  • 更多详情请参考question
  • 我可以像使用 Player1.DisplayBoard() 一样在用户模块中使用板模块,它会向我显示板。我不能做的是访问板模块中的功能 placeShip。
  • 我尝试在 Board 函数中移动该函数以创建一个属性,但后来我得到 placeShip 未定义
【解决方案2】:

app.js 可以创建一个对 child1 、 child2 等的引用。这个引用将允许对 child 的函数调用...

app.js 还可以“监听”在 child1、child2 等中触发的事件。

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

传递调用链是:

child1 可以通过触发其父级 (app.js) 中的调度程序正在侦听的事件来调用其兄弟姐妹中的一个函数

【讨论】:

  • 如何在 app.js 中引用 child 2?据我了解,我需要调用者成为玩家,以便玩家的董事会得到更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 2017-01-18
  • 1970-01-01
  • 2020-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多