在我的所有 Node 应用程序上扩展 Object.prototype.myNewMethod
我刚刚开始使用 NodeJs,所以我不熟悉这是否是一个好的实践,抱歉:(
我有我的对象实现,它将合并方法添加到我创建的所有对象中,这样我就可以合并到一个不同的对象中。
Object.prototype.merge = function(source){
//...my code here
return this;
}
所以 想知道如何使其可用于我的 Node 应用程序内的所有模块?
我 rel="nofollow">这本优秀的书,我可以为此创建一个模块,然后调用 utils.merge(obj1, obj2)
但是 我宁愿继续使用我的对象的实现,并且只需调用 obj1.merge(obj2)
是否有任何方法可以完成此任务?
。即便如此,
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需将您的实现放入一个文件中,并在应用的主
.js
文件中的其他任何内容之前需要它。objectmerge.js
;Object.prototype.merge = function(){ /body/};
main.js
:require('objectmerge.js');
// 继续你的代码
这样,您的
objectmerge.js
脚本将首先运行并在执行其他操作之前修改全局Object
。但是,我建议不要这样做,因为这不是常见的做法(并且它允许您在未明确定义的文件中使用
。foo.merge(bar)
对象.prototype.mergeJust 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 globalObject
before anything else. However, I'd recommend against it, as it isn't common practice (and that it allows you to usefoo.merge(bar)
in a file where you haven't explicitly definedObject.prototype.merge
.