我想扩展node.js的本地JSON
对象。在我的示例中,我能够扩展它以添加merge(json1, json2)
函数,该函数合并2个JSON:
JSON.merge = function(target) {
var sources = [].slice.call(arguments, 1);
sources.forEach(function (source) {
for (var prop in source) {
target[prop] = source[prop];
}
});
return target;
}
这个脚本的灵感来源于这个问题:Combine or merge JSON on node.js without jQuery
为了拥有更清晰的代码,我将此脚本放在库文件夹中,并在我的主脚本中要求它。这就是我做的......
我的lib/JSON.js
文件:
extends.merge = function(target){
// The same script as above.
}
并在我的app.js
文件中:
JSON = require('./lib/JSON')
它运行良好,但现在,原生JSON方法不起作用(如.stringify
)。然后我挖了一点,并尝试使用.prototype
扩展JSON,就像这样(在lib/JSON.js
中):
extends.prototype.merge = ...
但是得到以下错误:
TypeError: Cannot set property 'merge' of undefined
我真的不知道该做什么(以及我在做什么),因为解决问题会导致另一个问题。
请,需要帮助。
感谢。