面向对象的JavaScript 六 ---- javascript 继承方式总结

来源:互联网 发布:淘宝如何接入快递面单 编辑:程序博客网 时间:2024/06/05 08:01
文本主要对与12种继承的实现方式进行总结:

1.prototype chaining
Child。prototype = new Parent();
ECMA标准默认描述的机制,将所有的属性和方法被子类继承。

2.Inherit only the prototype
Child.prototype = Parent.prototype;
共享prototype对象,因为不必创建新的实例,导致效率更高.由于不是链式结构,所以查找继承方法和属性时更快.缺点是,子类可以修改父类的功能.

3.Temporaty constructor
function extend(Child,Parent)
{
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype =new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}

与第一种继承方式不同,这种继承方式只是继承prototype属性,在构造函数中定义的属性不会被继承.这种防护四用在YUI和Ext.js中.

4. Copying the prototype properties
funciton extends(Child, Parent)
{
    var p = Parent.prototype;
    var c = Child.prototype;
    for (var i in p)
    {
        c[i] = p[i];
    }
    c.uber = p;
}

通过拷贝prototype属性实现继承,不需要建立为了继承而构建对象,同时缩短了prototype链.

5.Copy all properties(shallow copy)
function extendCopy(p)
{
    var c={};
    for (var i in p)
    {
        c[i] = p[i];
    }
    c.uber=p;
    return c;
}

用过拷贝对象的属性实现继承,实现简单,早期的jQuery和prototype.js使用这种方法实现及策划那个.

6.Deep Copy
代码类似上一个方法,只是会用递归调用的方法来复制对象里的所用属性。现在的jQuery中使用这种方法实现继承。

7.Prototypal Inheritance
function object(o)
{
    function F(){};
    F.prototype = o;
    return new F();
}

8.Extend and Augment
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;
}
#7和#5的混合

9.Multiple inheritance
function multi()
{
    var n ={};
    var stuff;
    var j=0;
    var len = arguments.length;
    for (j=0;j<len;j++)
    {
        stuff = arguments[j];
        for (var i in stuff)
        {
            n[i] = stuff[i];
        }
    }
    return n;
}
这个方法可以实现多重继承

10.Parasitic inheritancs
function parasite(victim)
{
    var that = object(victim);
    that.more=1;
    return that;
}

11 Borrowing constructors
function Child()
{
    Parent.apply(this,augument);
}
改方法可以和#1结合可以很好的解决继承时,只是得到了父类属性引用的问题。

12 Borrow & Copy
function Child()
{
    Parent.apply(this,arguents);
}
extend2(Child,Parent);
结合#11和#4便面调用两次父类的构造函数。

终于介绍完了javascript中的所有继承的知识,之后的文章。我会介绍javascript中的一些设计模式。
原创粉丝点击