javascript - requirejs 导出的数组重置为 [] 文字不再导出

标签 javascript requirejs

我在模块 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
为什么?

谢谢

最佳答案

Why?

因为做

export.flows = [];

...创建一个数组并将其分配给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`

关于javascript - requirejs 导出的数组重置为 [] 文字不再导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22519229/

相关文章:

requirejs - AMD 结构化网络应用程序中的 Mixpanel 2.2 - 例如需要.js

javascript - ArcGis 3.5 问题与 Requirejs

java - Play Framework 2.3.7 : Static assets location not working in production

javascript - Javascript 中 url 的正则表达式

javascript - 点击后渲染模板

Javascript 找不到我的 mod_rewrite 查询字符串!

javascript - 将 window.location.href 与 Jquery Mobile 和 RequireJS 一起使用时如何避免出现空白页?

javascript - 如何使用 jsdoc 3 或 jsdoc 记录 Requirejs (AMD) 模块?

javascript - 获取 html url 变量

javascript - 设置 Cookie 路径