【发布时间】:2018-03-17 21:10:57
【问题描述】:
我有两个模块,在第一个模块中我声明了一个对象,因为我知道原语在 java 脚本中通过值传递,对象通过引用传递。我想从请求中获取响应状态,并且我将对象传递为一个引用,这样我就可以修改它的属性。问题是它没有做任何事情。最终值将是相同的。
//this code is in a different module from the other one
var variableToBeChanged = { something : "Initial value" };
anotherModule.changeValue(variableToBeChanged);
alert(variableToBeChanged.something);
//and in the other module I have a $.ajax and I want to get the response status(ex. 200)
//the code is sth like this:
function AnotherModule(ajax){
function changeValue(variableToBeChanged){
...
...
...
$.ajax({
...
...
...
success: function(data,xhr){
variableTobechanged.something = xhr.status;
}
});
}
}
最后它将显示:“初始值”而不是 200 或其他任何内容。 我在这里做错了什么?
【问题讨论】:
-
变量异步更改,因此您必须使用承诺或回调来访问新值
标签: javascript pass-by-reference multi-module