Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 419
Domenic Avatar asked Oct 11 '22 08:10

Domenic


1 Answers

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
like image 180
Wayne Avatar answered Oct 18 '22 02:10

Wayne