Domenic
Domenic

Reputation: 112817

Can I augment Object, Function, Date, etc. with "static methods" in Node?

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"?

Upvotes: 5

Views: 325

Answers (1)

Wayne
Wayne

Reputation: 60414

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

Upvotes: 4

Related Questions