2013-02-27 71 views
-2

有人可以解釋這三個函數是如何相互關聯的嗎?$在這裏做什麼功能?它有兩個定義嗎?

socket.onopen = function(){ 
    log("Welcome - status "+this.readyState); 
}; 

function $(id){ 
    return document.getElementById(id); 
} 

function log(msg){ 
    $("log").innerHTML+="<br>"+msg; 
} 

這些功能被寫入下方的客戶端代碼:

變種插座;

function init() { 
    var host = "ws://localhost:12345/websocket/server.php"; 
    try { 
     socket = new WebSocket(host); 
     log('WebSocket - status ' + socket.readyState); 
     socket.onopen = function (msg) { 
      log("Welcome - status " + this.readyState); 
     }; 
     socket.onmessage = function (msg) { 
      log("Received: " + msg.data); 
     }; 
     socket.onclose = function (msg) { 
      log("Disconnected - status " + this.readyState); 
     }; 
    } catch (ex) { 
     log(ex); 
    } 
    $("msg").focus(); 
} 

function send() { 
    var txt, msg; 
    txt = $("msg"); 
    msg = txt.value; 
    if (!msg) { 
     alert("Message can not be empty"); 
     return; 
    } 
    txt.value = ""; 
    txt.focus(); 
    try { 
     socket.send(msg); 
     log('Sent: ' + msg); 
    } catch (ex) { 
     log(ex); 
    } 
} 

function quit() { 
    log("Goodbye!"); 
    socket.close(); 
    socket = null; 
} // Utilities function $(id){ return document.getElementById(id); } function log(msg){ $("log").innerHTML+="<br>"+msg; } function onkey(event){ if(event.keyCode==13){ send(); } } 

回答

2

它聲明瞭一個名爲$其中以ID字符串函數,並返回

documet.getEelementById(id); 

簡單。

4

第一個函數調用第三個函數。第三個函數調用第二個函數。他們之間沒有其他關係。

$字符在變量名中沒有特殊含義。您可以改用foogetEl

$只是一個特別沒有意義的名字,因爲它是(a)short和(b)是一些在其他語言中用來指示變量的開始的字符,因此已經成爲受歡迎的函數。

0

改寫爲:

// Binds an anonymous function to the open event of the 
// object named socket. The handler function prints a 
// status message in the log panel by invoking the 
// function defined below named log. 

socket.onopen = function() { 
    log("Welcome - status " + this.readyState); 
}; 

// Function named $ that returns the DOM element 
// whose id attribute equals id. 

function $(id) { 
    return document.getElementById(id); 
} 

// Function named log that invokes the function named $. 
// 
// This function finds the DOM element whose id equals 
// "log" and appends a line break and a message to its 
// inner content. 

function log(msg) { 
    $("log").innerHTML += "<br>" + msg; 
} 
1

第一功能是事件處理程序。每當對象socket觸發open事件時,JavaScript將調用socket.onopen中定義的函數。該函數將調用下面定義的名爲log的另一個函數。

第二個函數爲document.getElementById()創建一個速記。由於$字符可以用作JavaScript中的常規標識符,因此它可以成爲縮短常見功能的便捷工具。這裏需要注意的是,幾個常見的js庫使用這個符號來實現關鍵功能,所以你應該在自定義代碼中避免這種情況。

log函數使用簡寫來選擇一個元素,通過串聯接收消息的文本。無論文本已經存在,都會將消息文本添加到文本中。