node.js需要Object.prototype?

我有点困惑,node.js require系统。

我知道如何exportrequire d组件的module.export函数,但不知道如何增强与原型js对象。

例如,我有一个代码,以通过prototype.watch方法来增强js Object。

我将在我自己的npm包中包含这些代码,并使用node require导入。

什么是最好的方式来做到这一点? 我需要重构这个代码作为一个function导出,需要执行后require吗? 谢谢。

 if (!Object.prototype.watch) { Object.defineProperty(Object.prototype, "watch", { enumerable: false, configurable: true, writable: false, value: function(prop, handler) { var oldval = this[prop], newval = oldval, getter = function() { return newval; }, setter = function(val) { oldval = newval; return newval = handler.call(this, prop, oldval, val); }; if (delete this[prop]) { // can't watch constants Object.defineProperty(this, prop, { get: getter, set: setter, enumerable: true, configurable: true }); } } }); } // object.unwatch if (!Object.prototype.unwatch) { Object.defineProperty(Object.prototype, "unwatch", { enumerable: false, configurable: true, writable: false, value: function(prop) { var val = this[prop]; delete this[prop]; // remove accessors this[prop] = val; } }); } 

node.js中的所有模块共享相同的全局范围。

require()它和你对全局对象所做的任何改变都会传播。