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();
  • 相关阅读:
    Generator函数执行器-co函数库源码解析
    前端解读Webview
    javascript设计模式详解之策略模式
    javascript设计模式详解之命令模式
    【VBA】标准Sub/Function定义,带ScreenUpdating、On Error GoTo
    【VBA】全局数组定义
    【VBA】全局常量定义
    调试Java代码(Eclipse)汇总
    为Eclipse添加反编译插件,更好的调试
    Eclipse图标含义
  • 原文地址:https://www.cnblogs.com/gresic/p/3394833.html
Copyright © 2011-2022 走看看