如何正确使用socket.io和oop

我喜欢node.js和socket.io,因为它们很强大,很漂亮,但是我的发展很less遇到问题。 这可能是因为我没有足够的练习node.js一个JavaScript的。

问题:有一个代码:

var express = require('express'); var sio = require('socket.io'); var X = require('./js/x.js'); var Y = require('./js/Y.js'); var app = express.createServer(); var ws = sio.listen(app); var users = []; app.use(express.static(__dirname + '/public')); ws.sockets.on('connection', function(socket) { users.push(new X(socket)); if (users.length === 2) { var z = new Y(users.shift(), users.shift()); z.listen(); } }); app.listen(9000); 

这里是X和Y:

 module.exports = function X(socket) { this.socket = socket; this.name = ''; X.prototype.setName = function(name) { this.name = name; }; }; module.exports = function Y(a, b) { this.a1 = a; this.a2 = b; this.variable1 = 777; Y.prototype.listen = function() { this.a1.socket.on('text', function(msg) { console.log('a1: ' + msg); // AND HERE IS MY ISSUE: // I want to access a2 by 'this' but 'this' doesn't point on 'class' Y this.a2.socket.emit('text', 'a1: ' + msg); // Also i want to change value of variable, something like that: this.a1.setName(msg); // AND: this.variable1--; }); }; 

我的问题是:如何和我做错了什么。 我是PHP开发人员,我意识到我的思维有所不同。 提前致谢!

由于你的callback函数不是Y的方法, this不会引用Y.

Javascript是一个有趣的语言, this是有趣的一部分( http://bonsaiden.github.io/JavaScript-Garden/#function.this )。

你可以这样做来解决这个问题:

 Y.prototype.listen = function() { var that = this; this.a1.socket.on('text', function(msg) { console.log('a1: ' + msg); that.a2.socket.emit('text', 'a1: ' + msg); that.a1.setName(msg); that.variable1--; }); } 

看看我刚刚引用的博客文章中复制的这个示例:

http://jsfiddle.net/UuHgh/

它返回5,因为count在闭包函数中被引用为外部variables。 但是,如果你添加this. 在计算增量closures之前,结果将是四。 这正是您为什么不参考Y.