下面的代码将创建一个新的new客户端套接字连接。我遇到的问题是如何获得socket对象的作用域。
如何在init()函数中引用套接字对象?
在下面的示例中,当在init()函数中执行this.socket时,它看起来像是在创建一个位于init函数本地的新的socket对象。
return webClient = {
clientConnection: null,
ioClient: null,
socket: null,
ready: false,
init: function(callback){
this.ioClient = require('socket.io-client');
console.log('Web Config :');
console.log(webClientConfig);
this.socket = this.ioClient.connect(webClientConfig.connectionString, {'forceNew':true });
this.socket.on('connect', function(){
console.log('Web Client Connected');
});
};发布于 2017-08-18 13:53:33
在此上下文中,该标识符指的是te webClient。
发布于 2017-08-18 13:57:12
全局声明一个变量以获取websocket连接,如下所示
var webSocket = require('socket.io-client');然后你可以在任何地方使用webSocket变量。喜欢
return webClient = {
clientConnection: null,
ioClient: null,
socket: null,
ready: false,
init: function(callback){
this.ioClient = webSocket;
console.log('Web Config :');
console.log(webClientConfig);
this.socket = this.ioClient.connect(webClientConfig.connectionString, {'forceNew':true });
this.socket.on('connect', function(){
console.log('Web Client Connected');
});
};发布于 2017-08-18 14:08:37
如果您期望(并且没有看到) this作为webClient.init中的webClient -您可以简单地这样做
var webClient = {
clientConnection: null,
ioClient: null,
socket: null,
ready: false,
init: function(callback){
webClient.ioClient = require('socket.io-client');
console.log('Web Config :');
console.log(webClientConfig);
webClient.socket = this.ioClient.connect(webClientConfig.connectionString, {'forceNew':true });
webClient.socket.on('connect', function(){
console.log('Web Client Connected');
});
};
return webClient;不过,我会把require('socket.io-client');作为一个全局
const ioClient = require('socket.io-client');
//
//
//
var webClient = {
clientConnection: null,
ioClient: null,
socket: null,
ready: false,
init: function(callback){
webClient.ioClient = ioClient;
console.log('Web Config :');
console.log(webClientConfig);
webClient.socket = this.ioClient.connect(webClientConfig.connectionString, {'forceNew':true });
webClient.socket.on('connect', function(){
console.log('Web Client Connected');
});
};
return webClient;https://stackoverflow.com/questions/45749303
复制相似问题