开发者

extending Object.prototype.myNewMethod over all my Node application

I've just started at NodeJs so I am not familiar whether this is a good practice or not, sorry :(

I have my Object implementation which add a merge method to all objects I create so I can merge to different objects in one.

Object开发者_StackOverflow社区.prototype.merge = function(source){
    //...my code here
    return this;
}

So I would like to know how I could make this available to all the modules inside my Node app?

I've read on this excellent book that I could create a module for that and then call utils.merge(obj1, obj2) for example.

But even so I'd rather keep using my object's implementation instead, and simply call obj1.merge(obj2)

is there any way to accomplish that?

Thanks in advance


Just put your implementation in a file and require it before anything else in the main .js file of your app.

  • objectmerge.js;

    Object.prototype.merge = function(){ /body/};

  • main.js:

    require('objectmerge.js'); // go on with your code

This way, your objectmerge.js script will run first and modify the global Object before anything else. However, I'd recommend against it, as it isn't common practice (and that it allows you to use foo.merge(bar) in a file where you haven't explicitly defined Object.prototype.merge.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜