无法更改对象的属性值-JavaScript

无法更改对象的属性值-JavaScript,javascript,json,ajax,Javascript,Json,Ajax,我的代码中有一个模块,无法更改对象属性的值。我在代码中有更详细的解释,请参见以下内容: var network = (function(){ // Created a closure. var ajax = { response: 0, // I set the initial value of response to 0 parse: function(x){ var y = JSON.parse(x); ajax.re

我的代码中有一个模块,无法更改对象属性的值。我在代码中有更详细的解释,请参见以下内容:

var network = (function(){ // Created a closure.
  var ajax = { 
    response: 0, // I set the initial value of response to 0
    parse: function(x){
             var y = JSON.parse(x);
             ajax.response = y; // This is where things don't seem to work. Value of response is still 0.
           }
    // Some other code.

    } // End of ajax object.

    return { // I return an Object .
     invoke: function(x){ ajax.parse(x); },
     reply: ajax.response
     }

})();

network.invoke(valid_argument); // I invoke the function and pass a valid json string received from a server via ajax.
console.log(network.reply); // I get 0, which is the initial value. Why?
正如代码中提到的,这个问题让人感觉很奇怪,我们非常感谢您的帮助

我得到0,这是初始值。为什么?

因为
reply:ajax.response
将执行该行时
ajax.response
具有的值分配给
reply
(其副本)。对
ajax.response的未来更改不会影响
reply
,这两个属性之间没有内在联系

以下是相同情况的简化示例:

var x = 42;
var y = x;
x = 21;
console.log(y); // still 42

JavaScript是,而不是。这意味着将值的副本分配给
reply
,而不是对
ajax.response
属性的引用。

@Teja:Felix King已经向您展示了技术方面,这是事实。我想就代码质量给出我的2美分。 Javascript允许我们以一种非常灵活的方式编写代码,而且看起来很混乱,Javascript代码很难阅读。所以你要编写代码片段,看得复杂些。避免过多地使用函数


@费利克斯·金:我认为传递值或传递引用在这里是不相关的。这些概念适用于传递给函数的参数的情况,而不是在赋值操作中。

函数中没有可用的响应。它在ajax对象中。ajax中的“a”代表异步?@brk Oops!这应该是回复,我现在更正了。你现在可以看一下吗?@adeneo yea..但是为什么现在需要这样做呢?如果我使用函数返回ajax.response的值会有帮助吗,因为它在运行时。如下所示:reply:function(){return ajax.response;}如果您的意思是
reply:function(){return ajax.response;}
,那么是的,因为
ajax.response
在每次调用
reply
时都会计算,而不是在构建对象时才计算一次。