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
     
     
     
  • 相关阅读:
    [BJOI2012]最多的方案(记忆化搜索)
    our happy ending(状压dp)
    [NOI2005]聪聪与可可(期望dp)
    CF983A Finite or not?(数学)
    [POI2012]STU-Well(二分答案+神仙操作)
    作诗2(玄学)
    IncDec Sequence(差分)
    [Vani有约会]雨天的尾巴(树上差分+线段树合并)
    合法括号序列(dp+组合数学)
    [SHOI2014]概率充电器(概率+换根dp)
  • 原文地址:https://www.cnblogs.com/erduyang/p/5647599.html
Copyright © 2011-2022 走看看