简体   繁体   English

在所有Node应用程序上扩展Object.prototype.myNewMethod

[英]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 :( 我刚开始在NodeJs工作,所以我不知道这是否是一个好习惯,对不起:(

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? 所以我想知道如何将其提供给Node应用程序中的所有模块使用?

I've read on this excellent book that I could create a module for that and then call utils.merge(obj1, obj2) for example. 我读过这本出色的书 ,我可以为此创建一个模块 ,然后调用utils.merge(obj1, obj2)

But even so I'd rather keep using my object's implementation instead, and simply call obj1.merge(obj2) 但是即使如此,我还是愿意继续使用对象的实现,而只需调用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. 只需将您的实现放入一个文件中,并在应用程序主.js文件中的其他任何文件之前要求它。

  • objectmerge.js ; objectmerge.js ;

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

  • main.js : main.js

    require('objectmerge.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. 这样,您的objectmerge.js脚本将首先运行并先修改全局Object 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 . 但是,我建议您不foo.merge(bar) ,因为这是不常见的做法(并且它允许您在尚未显式定义Object.prototype.merge的文件中使用foo.merge(bar)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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