从node.js模块中将原型函数添加到JSON
我正在看这个JavaScript库: https : //github.com/Canop/JSON.prune是为客户端浏览器devise的,我正在寻求将其移植到node.js
我希望能够在我的代码中的任何地方,我可以调用JSON.prune,它会输出一个string化对象的修剪版本。
它看起来像这样使用原型的概念将此function添加到JSON。 在node.js模块中做这件事的最佳实践是什么?
我想我会做一些模块,会说:
file prune.js ==== JSON.prototype.prune = function(){/*bla bla bla*/};
但是,不是只能在模块内部看到吗?
我需要说些什么吗?
file json2.js ===== exports = JSON; exports.prune = function(){/*bla bla bla*/
然后在我想访问的方法中,只是说
var JSON = require('json2.js');
获得扩展function? 这甚至会工作吗?
有没有更好的(更标准)的方式来做到这一点?
如果这是应用程序代码,而不是您正在编写的库或模块,则可以按照您喜欢的方式进行操作。 但是,就“最佳实践”而言,通常可以避免修改现有构造函数的原型。 最简单的方法是将其调整为像pruneJSON
这样的独立函数,而不是修改JSON
对象。
编辑:
对于这个特定的库,你可以像这样在最后修改代码(从第114行开始):
“`
pruneJSON = function (value, depthDecr, arrayMaxLength) { if (typeof depthDecr == "object") { var options = depthDecr; depthDecr = options.depthDecr; arrayMaxLength = options.arrayMaxLength; iterator = options.iterator || forEachEnumerableOwnProperty; if (options.allProperties) iterator = forEachProperty; else if (options.inheritedProperties) iterator = forEachEnumerableProperty } else { iterator = forEachEnumerableOwnProperty; } seen = []; depthDecr = depthDecr || DEFAULT_MAX_DEPTH; arrayMaxLength = arrayMaxLength || DEFAULT_ARRAY_MAX_LENGTH; return str('', {'': value}, depthDecr, arrayMaxLength); }; pruneJSON.log = function() { console.log.apply(console, Array.prototype.slice.call(arguments).map(function(v){return JSON.parse(pruneJSON(v))})); } pruneJSON.forEachProperty = forEachProperty; module.exports = pruneJSON;
“`