• 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
     
     
     
  • 相关阅读:
    less常用样式集,清除浮动、背景自适应、背景渐变、圆角、内外阴影、高度宽度计算。
    three.js是什么,能干嘛,和webgl什么关系
    网页兼容问题
    angular可自定义的对话框,弹窗指令
    three.js 相机camera位置属性设置详解
    移动端,PC端,微信等常用平台和浏览器判断
    css3,背景渐变,条纹,其它样式
    微信授权登录实现
    汉字转拼音
    springmvc json数据交互
  • 原文地址:https://www.cnblogs.com/erduyang/p/5647599.html
Copyright © 2020-2023  润新知