【问题标题】:how to make nodejs exports a static object如何让nodejs导出一个静态对象
【发布时间】:2015-04-16 10:00:45
【问题描述】:

我想知道下面的代码是否运行正确

a.js:

var obj = {
    name: 'a'
};
module.exports = obj;

b.js

var b = require('./a');

module.exports = b;

c.js

var a = require('./a');

console.log(a); // {name: 'a'}

a.name = 'b';
console.log(require('./a')); // {name: 'b'}
console.log(require('./b')); // {name: 'b'}

所以,我可以从外部更改模块导出

如果我将a.js 转换为a.json

a.json

{
    "name": "a"
}

我得到了同样的结果

我如何导出一个模块不能修改或覆盖外部表单

【问题讨论】:

    标签: node.js


    【解决方案1】:

    你可以冻结一个对象:

    // in order for people to not add properties through the prototype
    var o = Object.create(null);
    o.name = 'a';
    Object.freeze(o); // no one can change properties
    Object.seal(o); // no one can add properties;
    module.exports = o;
    

    如果您使用的是现代版本的 nodejs(阅读 io.js),您也可以使用代理:

    var o = {name: 'a'};
    var p = new Proxy(o, {
       set: function(obj, prop, value) {
           // unlike the freeze approach, this also throws in loose mode
           throw new TypeError("Can't set anything on this object");
       }
    });
    return p;
    

    也就是说,你在防备谁?为什么人们会在另一个模块中更改对象?

    【讨论】:

    • 谢谢,我只是好奇其他语言模块是否有与节点相同的操作?
    • @GilbertSun 这不是另一种语言,它只是“不推荐使用的节点”,节点运行在一个非常旧的 JavaScript 版本上,并且没有真正更新太多。 io.js 是所有贡献者在厌倦 node 运行方式时去的地方iojs.org
    • @GilbertSun 是的,它被称为变异对象。它在 manu 流行语言中很常见。
    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 2020-02-29
    • 2013-08-18
    相关资源
    最近更新 更多