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

标签 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.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?

正如代码中提到的,这个问题感觉很奇怪,感谢任何帮助。

最佳答案

I get 0, which is the initial value. Why?

因为reply: ajax.responsereply(其副本)分配给ajax.response处的值该行被执行的那一刻。 future 对 ajax.response 的更改不会影响 reply,这两个属性之间没有内在联系。

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

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

JavaScript 是 pass-by-value ,不是pass-by-reference 。这意味着该值的副本被分配给 reply,而不是对 ajax.response 属性的引用。

关于javascript - 无法更改对象属性的值 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44993638/

相关文章:

javascript - ie 中的 blob url 不起作用

javascript - 使用数组中的字符串名称运行函数

javascript - 检索 JSON 中的所有项目,而不仅仅是通过索引

javascript - 为什么事件监听器中的 "this"是窗口而不是元素?

android - 为 Rest 客户端设置 Json 内容类型

java - 在 Java 中比较两个 JSON 文件的最佳方法

javascript - 将字符串数组作为 jquery ajax 中的数据传递给 web api

java - Java 中的 JSON 与 Javascript 中的工作方式相同

javascript - Bootstrap AJAX 选项卡不起作用,没有任何反应

javascript - 数据表不显示内容的简单示例