我在模块A中定义一个数组,并希望通过模块B公开它
模块A的开头如下:
define(["require", "exports"], function(require, exports) {
exports.flows = [];
模块B的开头如下:
define(["require", "exports", 'A/A'], function(require, exports, A) {
exports.flows = A.flows;
当修改模块B中的数组时,它显然也会在模块A中被修改。像这样:
//in module B
exports.flows.push(1);
exports.flows.length //1
A.flows.length //1
但是当我重置(清空)模块A中的数组时,如下所示:
//in module A
exports.flows = [];
然后模块A和模块B中的数组将不再相同:
//in module B
exports.flows.length //1
A.flows.length //0
为什么呢?
由于
答案 0 :(得分:2)
为什么?
因为做了
export.flows = [];
...创建 new 数组并将其分配给export.flows
属性。这对引用旧数组的其他属性(或变量)没有任何影响。
这是一个更简单的例子:
var a = [];
var b = a; // `a` and `b` refer to the *same* array
a.push(1);
console.log(a.length); // 1
console.log(b.length); // 1, both `a` and `b` refer to the *same* array
a = []; // Now `a` refers to a different array, but `b` still
// refers to the previous one
console.log(a.length); // 0, because the new array is empty
console.log(b.length); // 1, because `b` doesn't refer to the same array as `a`