是否存在连接到 socket.io 的所有套接字的“原型(prototype)”?
我想定义一些可用于每个连接的套接字的函数。
目前我有:
io.sockets.on('connection', function(socket) {
//Define properties and functions for socket
socket.hello = function(){
console.log("hello from "+socket.id);
}
socket.hello();
});
但是我正在为每个套接字定义一个“新的”hello 函数。有套接字原型(prototype)吗?所以我可以有类似的东西:
Socket.prototype.hello = function(){
console.log("hello from "+socket.id);
}
io.sockets.on('connection', function(socket) {
socket.hello();
});
最佳答案
虽然它似乎无法通过主 require('socket.io')
获得。
目前,您必须require()
socket.js
直接引用它:
var Socket = require('socket.io/lib/socket');
Socket.prototype.hello = function () {
console.log("hello from " + this.id);
};
Note: From the
prototype
, you'll have to reference the instance asthis
. Asocket
variable won't already be available.Also, like the recommendations against modifying native types, like
Object
'sprototype
-- there's only oneSocket.prototype
, so it's possible to run into collisions of multiple modules trying to define the same method.
关于javascript - 在 socket.io 中向套接字添加功能的首选方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30110578/