我在命名空间中有一个JavaScript数组,如下所示:
app.collec.box = [];
Run Code Online (Sandbox Code Playgroud)
我在同一个命名空间内有一个函数,如下所示:
app.init = function () {
var box = this.collec.box;
// ... code to modify box
};
Run Code Online (Sandbox Code Playgroud)
我认为设置一个局部变量等于一个对象或对象属性只是对原始的一个参考,但似乎我错了,在box我的函数内部更改局部变量的内容后,app.collec.box不会改变.
请帮忙,我做错了什么?我该怎么解决这个问题?
提前致谢.
编辑.这是完整的代码.
var app = {
collec: {
box: [],
cache: []
},
init: function () {
var box = this.collec.box;
$.ajax({
url: 'file.json',
success: function (json) {
// Map JSON array to box array using Underscore.js _()map
box = _(json).map(function (o) {
return new Model(o);
});
}
});
}
};
app.init();
Run Code Online (Sandbox Code Playgroud)
引用指向对象,而不是变量.box不是对变量的引用this.collec.box; 相反,box它this.collec.box是对内存中一个特定对象的引用.您可以通过这些变量之一修改此对象的属性,但不能使用一个变量来修改另一个变量.
如果你想修改this.collec.box引用的内容,你需要直接设置它:
this.collec.box = ...;
Run Code Online (Sandbox Code Playgroud)
或使用this.collec对象的引用并修改其box属性:
var x = this.collec;
x.box = ...;
Run Code Online (Sandbox Code Playgroud)
编辑:也许一些图表可以让您更容易理解正在发生的事情.
分配时box = this.collec.box,这就是实际发生的情况:
this.collec.box -----> (object) <----- box
Run Code Online (Sandbox Code Playgroud)
两个变量都指向内存中的同一个对象,但box实际上并没有实际引用this.collec.box变量.
如果发生这种情况,您期望的是什么?
box -----> this.collec.box -----> (object)
Run Code Online (Sandbox Code Playgroud)
但这不会发生.