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();
  • 相关阅读:
    Ubuntu中的vsftpd配置
    Ubuntu学习-增加更新源及安装软件及卸载软件
    Ubuntu16.04下安装sublime text3
    需要读的书
    同一机器 部署 两个 jboss
    log4j 总结 精华
    oracle 笔记
    oracle 用户 多个表空间
    json
    json 基础
  • 原文地址:https://www.cnblogs.com/gresic/p/3394833.html
Copyright © 2011-2022 走看看