我的代码中有一个模块,但无法更改对象属性的值。我在代码中有更详细的解释,请参见下面:
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.response
将reply
(其副本)分配给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/