2013-01-07 27 views
0

我想了解socket.io的Javascript客戶端代碼是如何工作的。具體而言,我的目標是瞭解,它如何知道服務器的位置?瞭解socket.io.js

我在程序中使用的客戶端代碼很簡單 - 我只是鏈接到socket.io.js: - 自動插座

var socket = io.connect() 

就是這樣:

<script src="./socket.io/socket.io.js"></script> 

,然後連接到服務器。但它是如何知道的?

我看着socket.io.js,這是我發現了什麼(評論修剪):

var io = ('undefined' === typeof module ? {} : module.exports); 
(function() { 

/** Copyright(c) 2011 LearnBoost <[email protected]> * MIT Licensed */ 

(function (exports, global) { 
    var io = exports; 
    io.version = '0.9.11'; 
    io.protocol = 1; 
    io.transports = []; 
    io.j = []; 
    io.sockets = {}; 


    /** 
    * Manages connections to hosts. 
    * @param {String} uri 
    * @Param {Boolean} force creation of new socket (defaults to false) 
    * @api public 
    */ 
    io.connect = function (host, details) { 
    var uri = io.util.parseUri(host) 
     , uuri 
     , socket; 

    if (global && global.location) { 
     uri.protocol = uri.protocol || global.location.protocol.slice(0, -1); 
     uri.host = uri.host || (global.document 
     ? global.document.domain : global.location.hostname); 
     uri.port = uri.port || global.location.port; 
    } 

    uuri = io.util.uniqueUri(uri); 

    ... 

})('object' === typeof module ? module.exports : (this.io = {}), this); 
... 
})(); 

看來祕訣就是在「全球」參數,但是,到底是誰把「全球「到這個功能? (這是很難理解的功能,所有的括號...)

回答

0

您是在尋找的模式是這樣的:

(function (exports,global) { 
    ///content 
}) (<whatever>, this); 

this引用是在執行此功能範圍(這種模式既定義該函數並執行它),這恰好是全局範圍。有關JavaScript範圍的更多信息,請參閱此處 - http://tore.darell.no/pages/scope_in_javascript