设计模式——各种继承方式

一、原型继承

B.prototype=new A; 子类的原型等于父类的一个实例
把父类A中私有的属性和公有的属性都继承过来,变为子类B中公有的属性

     function A() {
            this.x = 100;
        }
        A.prototype = {
            constructor: A,
            getX: function () {
                console.log(this.x);
            }
        };
        function B() {
            this.y = 200;
        }
        B.prototype = new A;
        B.prototype.constructor = B;


二、call继承

在子类B的函数体中,把父类A当做普通函数执行,并且让父类A中的this变为子类B的一个实例,这样就相当于把父类A中的所有的私有的属性都增加给子类B的实例了
只能把A中私有的继承过来,当做B中私有的,公有属性的无法进行处理

        function A() {
            this.x = 100;
        }
        A.prototype = {
            constructor: A,
            getX: function () {
                console.log(this.x);
            }
        };
        function B() {
            this.y = 200;
            A.call(this);//-->A.call(b)
        }
        var b = new B;

  


三、冒充对象继承

在子类B的函数体中,先获取父类A的一个实例,然后遍历这个实例中的所有属性,把所有的属性依次赋值给子类B的实例的私有的属性
把A中公有的和私有的都变为了B中私有的

       function A() {
            this.x = 100;
        }
        A.prototype = {
            constructor: A,
            getX: function () {
                console.log(this.x);
            }
        };
        function B() {
            this.y = 200;
            var temp = new A;
            for (var key in temp) {
                if (key !== "constructor") {
                    this[key] = temp[key];
                }
            }
    //        this.temp = new A;
    //        for (var key in this.temp) {
    //            if (key !== "constructor") {
    //                this[key] = this.temp[key];
    //            }
    //        }
    //        delete this.temp;
        }
        var b = new B;
        console.dir(b);

 


四、混合模式:原型模式+call模式
A中私有的在B中私有的和公有的都存在了,A中公有的在B中公有的
虽然A中私有的重复了,但是没有太大的影响,如果非要私有的就是私有的,公有的就是公有的,我们只需要自己在编写一个程序把私有的删掉即可

 

        function A() {
            this.x = 100;
        }
        A.prototype = {
            constructor: A,
            getX: function () {
                console.log(this.x);
            }
        };
        function B() {
            this.y = 200;
            A.call(this);
        }
        B.prototype = new A;
        B.prototype.constructor = B;
        //将B公有中继承了A私有的删除掉,以下可以不写,除非你有强迫症
        B.prototype.delPrivate = (function () {
            var a = new A;
            for (var key in this) {
                if (a.hasOwnProperty(key)) {
                    delete this[key];
                }
            }
            return null;
        }).call(B.prototype);
        var b = new B;
        console.dir(b);

 

  

五、中间类继承:在IE下不兼容、我们一般用它只处理内置类

    function sum() {
        arguments.__proto__ = Array.prototype;
        arguments.sort(function (a, b) {
            return a - b;
        });
        return arguments;
    }
    console.log(sum(12, 23, 15, 23, 14, 15, 16, 10)); 
    

 

 

 

原文地址:https://www.cnblogs.com/cataway/p/5007183.html