2014-01-13 31 views
1

請參閱下面的簡化代碼。我觀察到,訪問userapp屬性xproducttype提供了2個不同的值 - 直接訪問時的初始(不正確)值,以及通過函數(getXproducttype)訪問時的(正確)值(稍後由某些代碼設置)。我不明白爲什麼我直接訪問屬性時沒有得到正確的值(例如,userapp.xproducttype)?只有當我定義一個函數(如getXproducttype)我得到正確的值(例如0)...訪問javascript對象的屬性給出錯誤的值

簡化代碼:

userapp = function(){ //module pattern 
//userapp properties 
var xproducttype = 1000; 

var getXproducttype = function(){ 
    return xproducttype; 
} 

var ready = function(callback){ 
    //here - before callback()- xproducttype is set to 0 by some code; 
    //no further code changes xproducttype again (!) 

    callback(); 
};//ready() 

return{ xproducttype:xproducttype, 
     getXproducttype:getXproducttype} 
}(); //userapp = function(){ 


$(document).ready(function(){ 

    userapp.ready(function() { 

    //between the next 2 console.log() code lines is no other code (!) 
    console.log('userapp.xproducttype: '+userapp.xproducttype); //returns the initial (wrong!) value 1000 
    console.log('userapp.getXproducttype(): '+userapp.getXproducttype()); //returns (correct!) value 0 set later 

    });//userapp.ready(function() 

}); //$(document).ready 
+0

任何人都可以解釋'userapp'如何獲得'ready'方法嗎? – Igor

+0

不知道我是否理解你的問題..ready()中的ready()是僅使用回調的已定義方法 – Joppo

+0

匿名函數返回並分配給'userapp'的對象只有一個屬性'xproducttype'和一個方法'getXproducttype' - 在顯示的代碼 – Igor

回答

1

當你做到這一點

return { xproducttype: xproducttype } 

你已經創建了一個新的獨立副本。最簡單的解決方案是如果可能的話總是使用吸氣劑。如果不是,則需要將xproducttype放在對象中,並將對該對象的引用傳遞給對象。

以下是如何堅持下去對象內:

var xproducttype = { 
    value: 1000; 
}; 

var getXproducttype = function() { 
    return xproducttype.value; 
}; 

return { 
    xproducttype: xproducttype, 
    getXproducttype: getXproducttype 
}; 

userapp.ready(function() { 
    // will now be the value you expect 
    console.log('userapp.xproducttype: '+userapp.xproducttype.value); 
}); 

的JavaScript總是按值傳遞的語言。這裏的訣竅是你傳遞一個對象的引用作爲你的值。所以你最終得到兩個參考副本,都指向同一個對象。

換句話說:在這種情況下使用對象允許您使用引用而不是基元。

+0

thnx您的評論。你能否詳細說明一下:「如果不是,你需要將xproducttype放在一個對象的內部,然後傳遞一個對象的引用」 - 也許有一個例子嗎? – Joppo

+0

當然,我增加了更多的回答 –

+0

thnx爲進一步補充(!) – Joppo