zoukankan      html  css  js  c++  java
  • ES5中的继承和ES6中的继承

    在JavaScript中,prototype、constructor、__proto__、构造函数、原型、实例这些概念已经很让人头疼,再加上ES6的class 、extends已经乱成一锅粥了,平时对这些用的少写的少,是得好好捋清楚。看了几篇文章有了自己的理解,理解如下:
     
    构造函数.prototype = 原型;
    构造函数.prototype.constructor = 原型.constructor = 构造函数;
    new 构造函数 = 实例;
    实例.constructor = 构造函数;
    实例.__proto__ = 原型;
     
    这样看着不直观,那就直接上张图,更直观的捋清楚这些概念之间的关系:
     
    下面用代码验证上面的关系:
     
    function CreateGf(name, age){
        this.name = name;
        this.age = age;
    }
     
    CreateGf.prototype.sayWhat = function(name){
        console.log(this.name + ' say: hi!');
    }
     
    var gf1 = new CreateGf('gf1',20);
    var gf2 = new CreateGf('gf2',22);
    gf1.sayWhat(gf1.name);
    gf2.sayWhat(gf2.name);
     
    console.log(CreateGf.prototype.constructor == CreateGf); //true
    console.log(gf1.constructor == CreateGf);  //true
    console.log(gf1.__proto__ == CreateGf.prototype); //true
     
    那在ES6中是什么样的呢?看下图:
     
     
    大体跟ES5中差不多,用代码验证下:
    class Point {
        constructor(x, y){
            this.x = x;
            this.y = y;
        }
     
        toString(){
            return '(' + this.x + ',' + this.y + ')';
        }
    }
     
    class ColorPoint extends Point{
        constructor(x, y, color){
            super(x,y);
            this.color = color;
        }
     
        toString(){
            return this.color + ':' + super.toString();
        }
    }
     
    let colorPoint = new ColorPoint();
     
    console.log(ColorPoint.prototype.__proto__ == Point.prototype); //true
    console.log(ColorPoint.__proto__ == Point); //true
     
     
     
  • 相关阅读:
    在前后端分离的SpringBoot项目中集成Shiro权限框架
    过账销售订单装箱单报错:用库存单位数量表示的实际剩余数量不能为零
    外部系统调用AX服务
    InventSum Closed and ClosedQty
    固定资产日志过账报错
    AX批处理相关
    AX2012打开报表报错
    有折扣的销售订单过账
    AX版本查询
    AX2012 SSRS Report 相关
  • 原文地址:https://www.cnblogs.com/erduyang/p/5647599.html
Copyright © 2011-2022 走看看