JavaScript Variabl范围

时间:2017-08-18 05:44:41

标签: javascript scope

以下代码将创建一个新的webclient套接字连接。我遇到的问题是如何获得套接字opbject的范围。

如何在init()函数中引用套接字对象?

使用以下示例在init()函数中执行this.socket时,似乎是在init函数的本地创建一个新的套接字对象。

    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');
        });
    };

3 个答案:

答案 0 :(得分:0)

在此上下文中,此标识符指的是te webClient。

答案 1 :(得分:0)

全局声明一个变量来获取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');
        });
    };

答案 2 :(得分:0)

如果您期望this webClient webClient.init 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;

但是,我将#log4j.logger.org.apache.synapse.transport.http.wire=DEBUG 作为全球

<div class="form-group">                        
    <label>Min Distance</label>
    <input type="text" class="form-control text-center" ng-model="minDistance"><br>
</div>
<div class="form-group">                        
    <label>Max Distance</label>
    <input type="text" class="form-control text-center" ng-model="maxDistance"><br>
</div>