JS中的原型继承和多重继承

概念:1原型继承是创建新类型对象----子类型,子类型基于父类型,子类型拥有父类型所有的属性和方法(从父类型继承得到),然后修改其中的部分内容或者添加新的内容。继承最好在子类型模型可以被视为父类型对象的时候使用。

    2从多个父类型中派生出一个对象类型称为多重继承。

原型继承:

使用new关键字和构造函数的prototype属性都是定义类型的特定方式,这些是我们到目前为止一直使用的,对于简单的对象,这种方式还是很好的,但是当程序过度使用继承时,这种创建对象的方法很快就显得笨拙了。所以增加一些函数作为常用操作符可以使其顺利一些。例如很多人都在对象上定义inherit方法和method方法。

        Object.prototype.inherit=function(baseConstructor){
            this.prototype = clone(baseConstructor.prototype);
            this.prototype.constructor=this;
        };
        Object.prototype.method=function(name,func){
            this.prototype[name]=func;
        };    


有了上面的信息,就可以像下面这样编码

        function StrangeArray(){}
        StrangeArray.inherit(Array);
        StrangeArray.method("push",function(value){
            Array.prototype.push.call(this,value);
            Array.prototype.push.call(this,value);
        });
        var strange=new StrangeArray();
        strange.push(4);//输出[4,4]


多重继承(混合类型):

实现多重继承的方式很多,下面的一个小例子是比较简单的而且多数情况下都适用的。

mix-in是一种特殊的原型,它可以混入到其他的原型里。SmallItem可以看做这样的一个原型。通过将它的方法复制到另一个原型里,其自身也混入了那个复制方法的原型。

        function mixInto(object,mixIn){
            forEachIn(mixIn,function(name,value){
                object[name] = value;

            });
        };
        var SmallDetailedItem = clone(DetailedItem);
        mixInto(SmallDetailedItem,SmallItem);

        var deadMouse = SmallDetailedItem.create("Fred the mouse","he is dead");
        deadMouse.inspect();
        deadMouse.kick();

还有下面的例子就是三种继承的实现。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
//The first way
function Person(name) { this.name = name; } Person.prototype.getName = function() { return this.name; } function Author(name, books) { this.books = books; } Author.prototype=new Person(name); Author.prototype.constructor=Author; Author.prototype.getBooks = function() { return this.books; } var au1=new Author("dororo1","Learn much"); var au2=new Author("dororo2","Learn less"); alert(au1.getName()); alert(au2.getName()); //The second way function Person(name) { this.name = name; } Person.prototype.getName = function() { return this.name; } function Author(name, books) { this.inherit=person; this.inherit(name); this.books = books; } var au=new Author("dororo","Learn much"); alert(au.getName()) ; //The thrid way function Person(name) { this.name = name; } Person.prototype.getName = function() { return this.name; } function Author(name, books) { this.base = new Person(name); for(var key in this.base){ if(!this[key]){ this[key]=this.base[key]; } } this.book=books; } var au1=new Author("dororo1","work"); var au2=new Author("dororo2","play"); alert(au1.getName()); alert(au2.getName()); au1.book; au2.book; </script> </head> <body> </body> </html>

 *part of the article from <<Eloquent JavaScript>>

原文地址:https://www.cnblogs.com/s-z-y/p/4490769.html