3

I'm wondering if there's a better way of doing this:

module.exports.foo = "bar";
module.exports.bar = "baz";
module.exports.foobar = "foobaz";

Now, I've heard about 'with' (and its dangers) but it doesn't work here because it can't add new properties to an object, it can only change existing properties. In fact if you try to add new properties you end up clobbering the enclosing scope which isn't very nice.

Something like this would be nice:

module.exports += {
  foo: "bar",
  bar: "baz",
  foobar: "foobaz"
}

But that converts both sides to strings before concatenating them which is not what I want.

Does such syntactic sugar exist in Node.JS-flavoured JavaScript? Maybe a function on 'module' to add lots of properties at once?

3 Answers 3

3

You could write a simple function to loop over them and add them to module.exports or you can try node.extend which tries to mimic jquery's $.extend()

Sign up to request clarification or add additional context in comments.

1 Comment

I think the loop is the lesser of those two evils.
1

Use Object.assign()

Object.assign(module.exports, {
              foo: "bar",
              bar: "baz",
              foobar: "foobaz"
            });

Comments

0

Consider using _.extend

So in your example:

            module.exports += {
              foo: "bar",
              bar: "baz",
              foobar: "foobaz"
            }

Would be:

            var _ = require('underscore');

            _.extend(module.exports,
                {
                  foo: "bar",
                  bar: "baz",
                  foobar: "foobaz"
                }
            );

Or, if you do not want any dependencies, using raw javascript:

            function myExtend(dest, obj) {
                for (key in obj) {
                    var val = obj[key];
                    dest[key] = val;
                }
            }
            myExtend(module.exports,
                {
                  foo: "bar",
                  bar: "baz",
                  foobar: "foobaz"
                }
            );

If you are using the latter method, make sure to check for edge cases, which I haven't here!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.