欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

變量沖突處理

 更新時間:2006年09月22日 00:00:00   作者:  
最近做了一階段的AJAX開發(fā),有一些心得體會。日后會慢慢寫出來,也請AJAXer多多指教~   剛開始寫AJAX代碼的時候,直接參照的是AJAX基礎教程一書中的代碼(該書真的很不錯,是AJAX入門的經典教材,是圖靈出版社的。計算機方面的書籍,我最信任的就是O'R和圖靈的)。   
   該書的創(chuàng)建XMLHttpRequest對象的代碼如下: 
var xmlHttp; 
function createXMLHttpRequest() {    if (window.ActiveXObject) {        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");    }     else if (window.XMLHttpRequest) {        xmlHttp = new XMLHttpRequest();    }} 
在一般情況下,該代碼的使用不會帶來任何問題。
如:
function test1(){ createXMLHttpRequest(); xmlHttp.onreadystatechange = handleStateChange1; url = "test.php?ts=" + new Date().getTime(); xmlHttp.open("GET", url, true); xmlHttp.send(null);}
function test2(){ createXMLHttpRequest(); xmlHttp.onreadystatechange = handleStateChange2; url = "test.php?ts=" + new Date().getTime(); xmlHttp.open("GET", url, true); xmlHttp.send(null);}

function handleStateChange1() {    ......
}


function handleStateChange2() {    ......
}
..........

在頁面的不同地方調用test1,test2函數都能正常工作。即不同時刻調用的話,就不會產生問題。

但是假如你需要在同一時刻同時調用這兩個函數,則會發(fā)現(xiàn)只有其中一個可以正常運行。
比如,我在加載頁面的時候運行如下函數:

function init(){ test1(); test2();}

此時,則test1,test2只有一個函數會正常執(zhí)行。

分析下原因,是由于javascript的語言特性導致。一般情況下,Javascript的變量,函數等等,都是公用的,其他對象都能訪問(可讀可寫)。這就是問題的所在。在同一時刻,調用test1和test2就會出現(xiàn)“變量xmlHttp”的沖突。

解決方法:

1  最簡單的方法,不要在同一時刻調用,如init函數可以改為:

function init(){ test1(); setTimeout("test2()",500);}

   但該方法屬于投機,并未真正解決問題。

2  修改“XMLHttpRequest創(chuàng)建函數”,改為一實例化函數。

function createXMLHttpRequest() {    if (window.ActiveXObject) {        var xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");    }     else if (window.XMLHttpRequest) {        var xmlHttpObj = new XMLHttpRequest();    } return xmlHttpObj;}

實例化時相應的改為:

function test1(){ xmlHttp_1 = createXMLHttpRequest(); 
 xmlHttp_1.onreadystatechange = handleStateChange1; url_1 = "test.php?ts=" + new Date().getTime(); xmlHttp_1.open("GET", url, true); xmlHttp_1.send(null);}



function test2(){ xmlHttp_2 = createXMLHttpRequest(); 
 xmlHttp_2.onreadystatechange = handleStateChange1; url_2 = "test.php?ts=" + new Date().getTime(); xmlHttp_2.open("GET", url, true); xmlHttp_2.send(null);}

這樣子處理的話,即使在同一時刻調用test1,test2函數,也不會產生問題了,實現(xiàn)了真正的“同步”。 

#######################################################
通過該方法,可以引申出javascript中對象的“私有屬性”的創(chuàng)建方法:
1 私有屬性可以在構造函數中使用 var 關鍵字定義。
2 私有屬性只能由特權函數公用訪問。(特權函數就是在構造函數中使用this關鍵字定義的函數)。外部客戶可以訪問特權函數,而且特權函數可以訪問對象的私有屬性。

比如下面這個Vehicle類,則wheelCount和curbWeightInPounds就是私有屬性,只能通過特權函數訪問/設置了:
function Vehicle() {    var wheelCount = 4;    var curbWeightInPounds = 4000;
    this.getWheelCount = function() {        return wheelCount;    }
    this.setWheelCount = function(count) {        wheelCount = count;    }
    this.getCurbWeightInPounds = function() {        return curbWeightInPounds;    }
    this.setCurbWeightInPounds = function(weight) {        curbWeightInPounds = weight;    }
 }

相關文章

最新評論