NodeJS对象要求

时间:2014-03-25 03:26:54

标签: javascript node.js object

场景:您登录到您的帐户,并使用数据库中的数据填充Player对象。该对象具有更新DB的方法。

问题:定义这样一个对象的最佳方法是什么?如何定义它以便节点可以随意使用这些方法?我是否需要将Player对象作为参数传递,或者我是否需要重新定义它(是否会重新定义对象?)req参数"是否会过期"或者是否有错误的范围?

module.exports = {
    createPlayer:Player
}

function Player(id,con,mysql,req) {
    this.id = id;
    this.x;
    this.y;
    this.con = con;
    this.mysql = mysql;
    this.req = req;
}

Player.prototype = {
    move:function() {

    }
}

最后,require如何用节点初始化它?

var player = (new require("Player")); //this is a guess to be honest

2 个答案:

答案 0 :(得分:1)

<强> player.js

function Player(id,con,mysql,req) {
    this.id = id;
    this.x;
    this.y;
    this.con = con;
    this.mysql = mysql;
    this.req = req;
}

Player.prototype = {
    move:function() {

    }
}

module.exports = Player;

立即在另一个档案中使用

var Player = require("./player");

// create player instance
var p = new Player(id,con,mysql,req);

答案 1 :(得分:1)

节点使用CommonJS作为其模块模式系统。关于节点调用这些对象的方式本身并不神奇。从某种意义上来说,它是“懒惰的”,直到第一次需要调用才初始化新模块。之后,默认情况下缓存对象的执行持续时间。

如果我理解你要做什么,我会改写你的例子:

// player.js
function Player(id,con,mysql,req) {
    this.id = id;
    this.x;
    this.y;
    this.con = con;
    this.mysql = mysql;
    this.req = req;
}

Player.prototype.move = function() {
    // logic
}

module.exports = function() {
     return new Player(arguments);
}

在您的服务器文件中:

var player = require('./player');

app.post('/player', function(req, res, next) {
    res.player = player(req.id, con, mysql, req);
    // at this point res.player is an instance of the object you wrote, with
    // everything populated, based on request
    // be careful as all objects are passed by reference, so if say mysql is your
    // mysql client, it can mutate and change unexpectedly.
});