Emulating pass by reference in JavaScript

☆樱花仙子☆ 提交于 2019-12-11 07:55:24

问题


All my unit tests have some common code I can run and abstract into a function. However I want to be able to re-use the Core value in every test

function makeSuite(name, module, callback) {
    suite(name, function () {
        var Core = {};

        setup(function () {
            Core = Object.create(core).constructor();
            Core.module("name", module);
        });

        teardown(function () {
            Core.destroy();
        });

        callback(Core);
    });
}

makeSuite("Server", server, function (Core) {
    test("server creates a server", useTheCore);

    test("server listens to a port", useTheCore);

    test("server emits express app", useTheCore);

    test("server destroys itself", useTheCore);
});

Each time I call useTheCore I expect there to be a different value of the core. This is because the particular unit test library calls the setup method before each test. This clearly does not work because I'm passing {} to the callback by value. And when I overwrite Core it does not propagate.

One hack I can use is __proto__ to emulate pass by reference

function makeSuite(name, module, callback) {
    suite(name, function () {
        var ref = {};

        setup(function () {
            var Core = ref.__proto__ = Object.create(core).constructor();
            Core.module("name", module);
        });

        teardown(function () {
            ref.__proto__.destroy();
        });

        callback(ref);
    });
}
  • Is there a more elegant way to emulate pass by reference, preferably not using the deprecated non-standard __proto__
  • Is there a more elegant solution to the actual problem of code re-use I have.

来源:https://stackoverflow.com/questions/8804881/emulating-pass-by-reference-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!