zoukankan      html  css  js  c++  java
  • Javascript混合模式实现继承

    为什么使用混合模式实现继承?

    实现对象的继承,我们可以通过对象冒充,也可以通过原型链的方式.

    但是,对象冒充就要求必须使用构造函数方式,而原型链则无法使用构造函数,那么,我们就综合一下,采区混合模式来实现继承.

    创建类的最好方式,是用构造函数定义属性,使用原型方式定义方法.这样的机制同样适用于继承机制,用对象冒充来继承构造函数的属性,用原型链继承prototype对象的方法.具体见下例:

    代码:

            function ClassA(color){
                this.color=color;
            }
            
            ClassA.prototype.getColor=function(){
                return this.color;
            }
            
            function ClassB(color,area){
                ClassA.call(this,color);
                this.area=area;
            }
            
            ClassB.prototype=new ClassA();
            ClassB.prototype.getArea=function(){
                return this.area;
            }
            
            var b = new ClassB('red',100);
            b.getColor();

    调试后的效果:

    image

    注意:

    这里我们主要看带斜体部分的两句.

    第一行代码采用对象冒充的方式实现了继承ClassA的color属性;

    第二行代码采用原型链的方式实现了继承ClassA的getColor方法.

    实例,选自<Javascript高级程序设计>:

            //基类--多边形
            function Polygon(sides){
                this.sides=sides;
            }
            
            Polygon.prototype.getArea=function(){
                return 0;
            }
            
            //子类--三角形继承于多边形
            function Triangle(base,height){
                Polygon.call(this,3);
                
                this.base=base;
                this.height=height;
            }
            
            Triangle.prototype=new Polygon();
            Triangle.prototype.getArea=function(){
                return 0.5*this.base*this.height;
            }
            
            //子类--长方形继承于多边形
            function Rectangle(base,height){
                Polygon.call(this,4);
                this.base=base;
                this.height=height;
            }
            
            Rectangle.prototype=new Polygon();
            Rectangle.prototype.getArea=function(){
                return this.base*this.height;
            }
            
            
            var tri = new Triangle(10,10);
            document.write(tri.getArea()+"<br/>");
            
            var rec = new Rectangle(10,10);
            document.write(rec.getArea())

    调试后的结果:

    变量tri:

    image

    变量rec:

    image

    页面结果:

    image

  • 相关阅读:
    Kth element of Two Sorted Arrays
    Populating Next Right Pointers in Each Node I && II
    Average waiting time of SJF and Round Robin scheduling
    LRU Cache
    Calculate H-index
    Get Level of a node in a Binary Tree
    Two Sum
    Intersection of Two Linked Lists
    Symmetric Tree
    Lowest Common Ancestor of Binary (Search) Tree
  • 原文地址:https://www.cnblogs.com/oneword/p/1624248.html
Copyright © 2011-2022 走看看