[英]Why do arrays update when variables don't?
Looking at the Javascript revealing module pattern below, the variable "defaultValue" does not update and needs a getter to access and updated value - explained here . 查看下面的Java代码显示模块模式,变量“ defaultValue”不会更新,需要使用getter来访问和更新值- 此处说明。
Why is it then, that an array (eg defaultArray) does update and can be accessed without a specific getter? 那么为什么数组(例如defaultArray)确实更新并且可以在没有特定getter的情况下进行访问?
Example Code: 示例代码:
var go = function () {
var defaultValue = null;
var defaultArray = [];
var setDefaultValue = function (newObj) {
for (var i = 0; i < 5; i++) {
if (i == 2) {
defaultValue = newObj;
defaultArray.push(newObj);
}
}
};
var getDefault = function () {
return defaultValue;
};
return {
defaultValue: defaultValue,
setDefaultValue: setDefaultValue,
getDefault: getDefault,
defaultArray: defaultArray,
};
};
window.onload = function () {
var ans = new go();
ans.setDefaultValue({ test: 'ok', unos: 123 })
// At this point, defaultArray has updated, but defaultValue has not
var thisWillBeNull = ans.defaultValue;
var thisWillHaveAValue = ans.defaultArray;
// Can get the value
var newDefault = ans.getDefault();
};
The difference is in editing the variables themselves vs. the object they reference. 区别在于编辑变量本身与引用的对象之间。
When assigning one variable or property to another, the value is always copied and the variables/properties remain independent of each other. 将一个变量或属性分配给另一个变量或属性时,始终会复制该值,并且变量/属性保持彼此独立。
// defaultValue: defaultValue
defaultValue ------\
>--- null
ans.defaultValue --/
// defaultArray: defaultArray
defaultArray ------\
>--- []
ans.defaultArray --/
The reassignment to defaultArray
within setDefaultValue()
is actually altering the variable, but doesn't have any affect on the property. setDefaultValue()
对defaultArray
的重新分配实际上是在更改变量,但对属性没有任何影响。
defaultValue ------- { test: 'ok', unos: 123 }
ans.defaultValue --- null
While the .push()
is altering the Array
instance itself, leaving both the variable and property unchanged as holding references to the Array. 当
.push()
更改Array
实例本身时,变量和属性均保持对Array的引用不变。
defaultArray --------\
>--- [
/ 0: { test: 'ok', unos: 123 }
/ ]
ans.defaultArray --/
By defining the property as a getter and/or setter , it will no longer hold its own value and will be dependent upon the variable: 通过将属性定义为getter和/或setter ,它将不再拥有自己的值,并将依赖于变量:
return {
get defaultValue() {
return defaultValue;
},
// ...
};
ans.defaultValue ----> defaultValue ----> null
ans.defaultValue ----> defaultValue ----> { test: 'ok', unos: 123 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.