是否有更好的方法来合并两个对象并调用父函数?
var a = {
a:1,
myFunction:function(){
console.info("a");
}
}
var b = {
b:2,
myFunction:function(){
console.info("b");
this.callParent();
}
}
var obj = {};
$.extend(obj, a);
$.extend(obj, b);
b = obj;
b.superclass = a;
包装所有函数,以便出现“this.callParent”
function wrap(func, parent) {
return function() {
this.callParent = parent;
var result = func.apply(this, arguments);
return (this.callParent), result;
};
}
迭代如下:
$.each(b, function(key, value){
if(typeof value == "function" && b.superclass && b.superclass[key]){
b[key] = wrap(value, b.superclass[key]);
}
});
输出为“b -> a”:
b.myFunction();
最佳答案
Is there a better method for merging two objects and calling parent functions?
是的,使用单个辅助函数一步完成,而不是使用 $.extend
那样的错误方式。
请注意,jQuery 的 extend
函数并没有真正设置任何继承,它只是可用于混合 - 您不应该在引用中使用术语“继承”。另外,您的对象 a
和 b
绝对不是“类”,因此请不要将其命名为 .superclass
。他们充其量只是单例。
您可以按照您建议的方式进行继承,但请注意,它不是 JavaScript 中所期望的原型(prototype)继承。
function inheritObject(parent, child) {
for (var p in parent)
if (!(p in child))
child[p] = parent[p]; // extend
else if (typeof child[p] == "function") (function(name, fn) {
child[name] = function() { // inherit
this.callParent = parent[name];
var res = fn.apply(this, arguments);
delete this.callParent;
return res;
};
}(p, child[p]));
return child;
}
var a = {
a:1,
myFunction:function(){
console.info("a");
}
}
var b = inheritObject(a, {
b:2,
myFunction:function(){
console.info("b");
this.callParent();
}
});
关于JavaScript 继承与 jQuery - 调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22073059/