• 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();
  • 相关阅读:
    Section 3.1 Shaping Regions
    3D@OpenSource
    查找资料
    Section 3.1 Shaping Regions Again
    USACO Contact IOI’98 TLE
    事项ON丰宁坝上草原
    四叉树@POJ1610 Quad Trees
    在TabCtrl上放View@MFC
    CUGB的一场周赛
    贴图程序进展
  • 原文地址:https://www.cnblogs.com/gresic/p/3394833.html
Copyright © 2020-2023  润新知