请参阅下面的简化代码。我观察到访问userapp的属性xproducttype提供了2个不同的值 - 直接访问时的初始(不正确)值,以及通过函数(getXproducttype)访问时的(正确的)值(稍后由某些代码设置)。我不明白为什么我直接访问该属性时没有得到正确的值(例如,userapp.xproducttype)?只有当我定义一个函数(比如getXproducttype)时,我得到正确的值(例子中为0)......
简化代码:
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 :(得分:1)
当你这样做时
return { xproducttype: xproducttype }
您已创建了一个新的单独副本。最简单的解决方案是尽可能使用getter。如果没有,您将需要在对象内部粘贴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总是通过价值语言传递。这里的技巧是您将对象的引用作为您的值传递。因此,您最终得到两个引用副本,它们都指向同一个对象。
换句话说:在这种情况下使用对象允许您使用引用而不是基元。