zoukankan      html  css  js  c++  java
  • js的继承实现方式

    第一种 prototype 引用型原型继承
    语言支持:js原生支持的继承方式 构造器的的prototype属性作为类的原型 每个该类的对象都持有一个到原型的引用 当对象中的属性不存在时 可以访问原型的属性
    代码示例:

     
    第二种 复制型原型继承
    语言支持:js new运算符的性质 当构造函数return值为非空对象时 new表达式返回return的对象
    代码示例:

     
    第三种 类继承 属性抄写
    语言支持:for in枚举对象所有属性
    代码:

     
    第四种 类继承 对象冒充
    语言支持: 1.动态添加和删除方法 2.函数的call和apply
    代码:
    用语言支持1实现的类继承


    用语言支持2实现的类继承

    第五种 原型抄写
    语言支持:通过修改类的原型对象 可以为一类对象添加属性和方法
    代码:

     
    第六种 元类
    语言支持: js函数都是对象 且js函数可被构造
    代码:

     

    以下通过混合构造函数与原型方式来实现JS的继承功能。 Polygon为父类,Triangle Rectangle 为子类。
    function Polygon (iSiders){
        this.sides = iSiders;
    }
    Polygon.prototype.getArea = function(){
        return 0;
    }


    function Triangle(iBase,iHeight){
        Polygon.call(this,3);
        this.base = iBase;
        this.height = iHeight;
    }
    Triangle.prototype = new Polygon();
    Triangle.prototype.getArea = function(){
        return 0.5*this.base*this.height;
    }

    function Rectangle(iLength,iWidth){
        Polygon.call(this,4);
        this.length = iLength;
        this.width = iWidth;
    }
    Rectangle.prototype = new Polygon();
    Rectangle.prototype.getArea = function(){
        return this.length*this.width;
    }
    var triangle = new Triangle(12,4);
    var rectangle = new Rectangle(22,10);
    alert(triangle.getArea);
    alert(rectangle.getArea);<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

  • 相关阅读:
    leetcode 309. Best Time to Buy and Sell Stock with Cooldown
    leetcode 714. Best Time to Buy and Sell Stock with Transaction Fee
    leetcode 32. Longest Valid Parentheses
    leetcode 224. Basic Calculator
    leetcode 540. Single Element in a Sorted Array
    leetcode 109. Convert Sorted List to Binary Search Tree
    leetcode 3. Longest Substring Without Repeating Characters
    leetcode 84. Largest Rectangle in Histogram
    leetcode 338. Counting Bits
    git教程之回到过去,版本对比
  • 原文地址:https://www.cnblogs.com/CharmingDang/p/9663800.html
Copyright © 2011-2022 走看看