我想知道是否有一些最佳实践如何在 javascript (nodejs) 中为从外部(数据库、网络等)接收的对象提供行为。
例如,假设我有一些 getById(<Id>)
从数据库获取正确对象的函数,您将如何添加 save
该函数返回的对象上的方法?
这是我想要的:
var getById = function (id) {
var obj = callSomeExternalCode(id);
return obj;
};
var myObj = getById('1234');
myObj.aProperty = 'a_new_value';
myObj.save();
我宁愿避免伪经典解决方案(无论如何,如果你能为我提供一个好的解决方案,我可能会根据我的风格进行调整)
编辑:我忘了提及,如果能在单独的“父”对象中定义这些方法,那就太好了(即使我认为原始继承不是答案)
谢谢
最佳答案
it would be very nice to have these methods defined in a separate 'parent' object
然后就这样做:
var parent = {
save: function() {…}
};
function getById(id) {
// There's a shortcut function called "extend" for this in many libs:
// return extend(callSomeExternalCode(id), parent);
// which does
var obj = callSomeExternalCode(id);
for (var p in parent)
obj[p] = parent[p]; // copy
return obj;
}
I suppose, proto-inheritance is not the answer
有可能,特别是当 parent
上的属性多于新 obj
上的属性时。然后你可以这样做(即使没有任何伪经典代码):
function getById(id) {
// return extend(Object.create(parent), callSomeExternalCode(id));
// long:
var obj = callSomeExternalCode(id),
res = Object.create(parent);
for (var p in obj)
res[p] = obj[p]; // copy
return res;
}
关于javascript - 如何在 javascript 中使用自定义方法来增强对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16025021/