5

If I create a Node.js module "augs" that contains

Object.foo = "bar";

Then type in the REPL

require("./augs");
typeof Object.foo

I get back 'undefined'.

We have a significant amount of code in our web app that relies on convenience methods added to Object, Function, Date, etc. We're trying to share some code between the frontend and the backend, but it seems like Node resets these constructor functions, or somehow otherwise prevents changes to them in a given module from leaking into other modules. While this is pretty smart and I appreciate the level of protection, is there some way to say "I know what I'm doing; please let me augment Object"?

1 Answer 1

4

Assuming augs.js contains the following:

exports.augment = function(o) {
    o.foo = "bar";
}

Augment Object like this:

> var aug = require("./augs.js");
> aug.augment(Object);
> typeof Object.foo
'string'

Note: Assume you also export the following function:

exports.getObject = function () {
    return Object;
}

Then:

> var aug = require("./augs.js")
> aug.getObject() == Object
false
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, I guess this would work; I would have to convert our (rather large) augs.js to an exporting module, though, which kind of sucks. Thanks also for pointing out that Object from one module is not == Object from another module.
@lwburk can you elaborate on Object being different in different modules?
@Peter - Simply put, the natives in a module are not the same natives as those in the script that loaded that module. Also: "Currently as of Modules 1.1 the spec for how an environment chooses to implement native classes in Modules is "undefined". That means it's up to each environment implementation to decide how it should work." wiki.commonjs.org/wiki/Modules/Natives
@lwburk Thanks for that! Has interesting implications and probably more pros (probably better interoperability and fewer collisions and inadvertent bugs) and cons (harder to magically monkey-patch, more complicated to understand and explain).

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.