javascript实现继承的12种套路

如果你已经习惯了从“类”的角度去理解和分析问题,那么基于构造函数的继承实现比较适合你,01~06方式都是基于构造函数的。
如果你只是处理某些具体对象或实例,那么基于对象的继承实现比较适合你,07~12方式都是基于对象的。

编号原型链示例
01 原型链(经典模式)
Child.prototype = new Parent();
                        
02 仅继承父构造函数的原型
Child.prototype = Parent.prototype;
                        
03 借用构造函数
function Child() {
    Parent.apply(this, arguments);
}
                        
04 临时构造函数
function extend(Child,Parent) {
    var F = function() {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;
}
                        
05 复制父构造函数的原型属性
function extend2(Child, Parent) {
    var p = Parent.prototype;
    var c = Child.prototype;
    for (vari in p) {
        c[i] = p[i];
    }
    c.uber = p;
}
                        
06 借用构造函数并拷贝原型
function Child() {
    Parent.apply(this, arguments);
}

extend2(Child,Parent);
                        
07 基于对象的浅拷贝
function shallowCopy(p) {
    var c = {};
    for (var i in p) {
        c[i] = p[i];
    }
    c.uber = p;
    return c;
}
                        
08 基于对象的深拷贝
function shallowCopy(p) {
    var c = {};
    for (var i in p) {
        c[i] = p[i];
    }
    c.uber = p;
    return c;
}
                        
09 原型继承
function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}
                        
10 原型继承与属性拷贝的混合模式
function objectPlus(o, stuff) {
    var n;

    function F() {}
    F.prototype = o;
    n = new F();
    n.uber = o;
    for (var i in stuff) {
        n[i] = stuff[i];
    }
    return n;
}
                        
11 多重继承
function multi() {
    var n = {},stuff, j = 0,len = arguments.length;
    for (j = 0; j < len; j++) {
        stuff = arguments[j];
        for (var i in stuff) {
            n[i] = stuff[i];
        }
    }
    return n;
}
                        
12 寄生继承
function parasite(victim) {
    var that = object(victim);
    that.more = 1;
    return that;
}
                        

参数链接:http://www.cnblogs.com/keepfool/p/5592256.html

原文地址:https://www.cnblogs.com/miid/p/5659020.html