【问题标题】:JavaScript inheritance with jQuery - calling parent function使用 jQuery 的 JavaScript 继承 - 调用父函数
【发布时间】:2014-02-27 15:31:30
【问题描述】:

有没有更好的方法来合并两个对象并调用父函数?

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();

Demo

【问题讨论】:

  • 一般的 jQuery 和 $.extend(); 与 JavaScript 中的继承无关。所有$.extend() 所做的只是合并2 个对象,它不太关心prototypeprototype.constructor$.extend(objA, objB) 也不会导致objA instanceof objB 为真。说 JavaScript 继承与 jQuery 是非常误导的。

标签: javascript jquery object inheritance parent


【解决方案1】:

有没有更好的方法来合并两个对象并调用父函数?

是的,使用单个辅助函数一步完成,而不是使用 $.extend 的那种笨拙的方式。

请注意,jQuery 的 extend 函数并没有真正设置任何继承,它只是可以用于混合 - 您不应该在引用中使用术语“继承”。另外,您的对象ab 绝对不是“类”,所以请不要将其命名为.superclass。他们充其量只是单身。

您可以按照您建议的方式进行继承,但请注意它不像 JavaScript 中所期望的那样原型继承

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();
    }
});

【讨论】:

    猜你喜欢
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多