开发者

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜