zoukankan      html  css  js  c++  java
  • JavaScripta面向对象之继承

    最近一直在看Nicholas C.Zakas的《JavaScript高级程序设计》

    看到面向对象编程时,就自己连抄带编总结了一下。

    由于自己对很多概念理解不是过于透彻,所以以代码为主,以后会慢慢更新加上自己的理解

    如有不妥或者错误之处,还请斧正

    一、对象冒充

    function ClassA(sColor){
        this.color=sColor;
        this.sayColor=function(){
            alert(this.color);
        }
    }
    
    function ClassB(sColor,sName){
        this.showColor=ClassA;
        this.showColor(sColor);
        delete this.showColor;
    
        this.name=sName;
        this.sayName=function(){
            alert(this.name);
        }
    }
    
    var test=new ClassB('red','color');
    test.sayColor();
    test.sayName();

    二、call()方法

    function ClassA(sColor){
        this.color=sColor;
        this.sayColor=function(){
            alert(this.color);
        }
    }
    
    function ClassB(sColor,sName){
        ClassA.call(this,sColor);
    
        this.name=sName;
        this.sayName=function(){
            alert(this.name);
        };
    }
    
    var test=new ClassB('red','color');
    test.sayColor();
    test.sayName();

    三、apply()方法

    function ClassA(sColor){
        this.color=sColor;
        this.sayColor=function(){
            alert(this.color);
        }
    }
    
    function ClassB(sColor,sName){
        ClassA.call(this,sColor);
    
        this.name=sName;
        this.sayName=function(){
            alert(this.name);
        };
    }
    
    var test=new ClassB('red','color');
    test.sayColor();
    test.sayName();

    四、原型链方法

    function ClassA(){};
    ClassA.prototype.color='red';
    ClassA.prototype.sayColor=function(){
        alert(this.color);
    };
    
    function ClassB(){};
    ClassB.prototype=new ClassA();
    var test=new ClassB();
    test.sayColor();

    五、混合模式

    //类A的属性
    function ClassA(sColor){
        this.color=sColor;
    }
    //类A的方法
    ClassA.prototype.sayColor=function(){
        alert(this.color);
    };
    //类B继承A的属性
    function ClassB(sColor,sName){
        ClassA.call(this,sColor);
        this.name=sName;
    }
    //类B继承A的方法
    ClassB.prototype=new ClassA();
    //类B自己的方法
    ClassB.prototype.sayName=function(){
        alert(this.name);
    }
    
    var test=new ClassB('red','color');
    test.sayColor();
    test.sayName();
  • 相关阅读:
    DevExpress XtraTabbedMdiManager删除Page
    Winform 窗体获得焦点
    leaflet 整合 esri
    使用 Leaflet 显示 ArcGIS 生成西安80坐标的地图缓存
    收藏一些编码舒服的cnblog博客园 博客
    获取字符串中的可能身份证号 并验证
    ASP.NET 的烂问题 -- 加载、创建c++项目失败
    ASP.NET 的烂问题
    sublime text3 解决打开文件中文乱码问题
    [转载]function与感叹号(转)
  • 原文地址:https://www.cnblogs.com/gresic/p/3394833.html
Copyright © 2011-2022 走看看