請參閱下面的簡化代碼。我觀察到,訪問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
任何人都可以解釋'userapp'如何獲得'ready'方法嗎? – Igor
不知道我是否理解你的問題..ready()中的ready()是僅使用回調的已定義方法 – Joppo
匿名函數返回並分配給'userapp'的對象只有一個屬性'xproducttype'和一個方法'getXproducttype' - 在顯示的代碼 – Igor