zoukankan      html  css  js  c++  java
  • 模拟 extjs 底层继承

    1、混合继承的弊端

      混合继承在继承原型的时候,其实将 父类的模板 再次继承,影响效率

      

     // 混合继承
        function Person(name,age) {
            this.name = name;
            this.age = age;
        }
        Person.prototype = {
            constructor : Person,
            sayHello : function () {
                alert("hello");
            }
        }
    
        function Boy(name,age,sex) {
            //Person.call(this,name,age);
            this.sex = sex;
        }
        Boy.prototype = new Person();           //  虽然 在 new Person 的时候,并没有传入参数,但是 还是实例化了 Person 模板 , 只是参数的值默认为 undefined
    
        var b = new Boy("z3",25,"");
        alert(b.name);          // undefined
        alert(b.sex);           //

    改进方法 

     // 改进方法 , 模拟 extjs 底层继承实现方式
        function Person(name,age) {
            this.name = name;
            this.age = age;
        }
        Person.prototype = {
            constructor : Person,
            sayHello : function () {
                alert("hello");
            }
        }
    
        function Boy(name,age,sex) {
            Boy.superClass.constructor.call(this,name,age);
            this.sex = sex;
        }
    
        function extend(sub,sup) {
            var F = new Function();
            F.prototype = sup.prototype;
            sub.prototype = new F();
            sub.prototype.constructor = sub;
            sub.superClass = sup.prototype;
            if(sup.prototype.constructor = Object.prototype.constructor){
                sup.prototype.constructor = sup;
            }
        }
        extend(Boy,Person);
        var b = new Boy("z3",25,"");
        alert(b.name);              // z3
  • 相关阅读:
    112.路径总和
    二叉树的中序遍历
    HTML基础及案例
    web概念概述
    Spring JDBC
    数据库连接池
    JDBC连接池&JDBCTemplate
    JDBC
    MySQL多表&事务
    DCL
  • 原文地址:https://www.cnblogs.com/debra/p/7898504.html
Copyright © 2011-2022 走看看