我有一个关于通过引用传递的问题。特别是我将wf
传递给wordFormUpdateSubmit。
当我这样做时:wf = response.data;
它不会改变word.wordForms中的任何内容
当我这样做时:self.word.wordForms[key] = response.data;
它正确地更改了word.wordForms中的wf内容
我的问题是为什么不通过引用传递,为什么wf = response.data;
不起作用?
wordFormCheckAndUpdate = (): ng.IPromise<any> => {
var self = this;
var promises = [];
angular.forEach(self.word.wordForms, function (wf, key) {
var updatePromise = self.wordFormUpdateSubmit(wf, key);
promises.push(updatePromise);
});
return self.$q.all(promises);
};
wordFormUpdateSubmit = (wf: IWordForm, key: number): ng.IPromise<any> => {
var self = this;
return self.$http({
url: self.ac.dataServer + "/api/WordForm/Put",
method: "PUT",
data: wf
})
.then(
(any => {
// This does not correctly populate self.word.wordForms[0]
wf = response.data;
// This works
self.word.wordForms[key] = response.data;
});
}
答案 0 :(得分:2)
JavaScript没有传递引用,它有“call by sharing”。
如果为函数参数指定新值,则不会对传递给函数的原始值进行任何更改。它只会覆盖参数。
这应该是您尝试做的可行(和更清洁)的替代方案:
wordFormCheckAndUpdate = (): ng.IPromise<any> => {
var self = this;
return self.$q.all(self.word.wordForms.map((wf, key) =>
self.wordFormUpdateSubmit(wf, key)
))
.then(function (values) {
self.word.wordForms = values;
});
};
wordFormUpdateSubmit = (wf: IWordForm, key: number): ng.IPromise<any> => {
var self = this;
return self.$http({
url: self.ac.dataServer + "/api/WordForm/Put",
method: "PUT",
data: wf
})
.then(response => response.data);
}