简体   繁体   中英

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.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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM