访问javascript对象的属性时给出了错误的值

访问javascript对象的属性时给出了错误的值,javascript,Javascript,请看下面的简化代码。我观察到,访问userapp的属性xproducttype时会提供两个不同的值—直接访问时的初始(不正确)值,以及通过函数(getXproducttype)访问时的(正确)值(稍后由一些代码设置)。我不明白为什么在直接访问属性(例如,userapp.xproducttype)时无法获得正确的值?只有当我定义一个函数(如getXproducttype)时,我才能得到正确的值(示例中为0) 简化代码: userapp = function(){ //module pattern

请看下面的简化代码。我观察到,访问userapp的属性xproducttype时会提供两个不同的值—直接访问时的初始(不正确)值,以及通过函数(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
当你这么做的时候

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始终是一种传递值语言。这里的诀窍是将对对象的引用作为值传递。因此,最终会得到引用的两个副本,它们都指向同一个对象


换句话说:在这种情况下使用对象可以让您使用引用而不是原语。

有人能解释一下
userapp
如何获得
ready
方法吗?我不确定是否理解您的问题..ready()在userapp中,只是一个使用回调的已定义方法。匿名函数返回并分配给
userapp
的对象在代码showntnx中只有一个属性
xproducttype
和一个方法
getXproducttype
,以供注释。请您详细说明一下“如果没有,您需要将xproducttype粘贴到一个对象中,并传递对该对象的引用”-也许可以举个例子吗?当然,为了进一步解释(!),我在我的回答中添加了更多内容