ES5中的继承和ES6中的继承
2016-07-06 17:37
465 查看
在JavaScript中,prototype、constructor、__proto__、构造函数、原型、实例这些概念已经很让人头疼,再加上ES6的class 、extends已经乱成一锅粥了,平时对这些用的少写的少,是得好好捋清楚。看了几篇文章有了自己的理解,理解如下:
构造函数.prototype = 原型;
构造函数.prototype.constructor = 原型.constructor = 构造函数;
new 构造函数 = 实例;
实例.constructor = 构造函数;
实例.__proto__ = 原型;
这样看着不直观,那就直接上张图,更直观的捋清楚这些概念之间的关系:
下面用代码验证上面的关系:
那在ES6中是什么样的呢?看下图:
大体跟ES5中差不多,用代码验证下:
构造函数.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
相关文章推荐
- python实现根据两点经纬度计算实际距离
- leetcode.371. Sum of Two Integers
- 罪人审判
- Spring常用注解
- 升级centos6.6至centos7.2.1511
- 25个Java机器学习工具&库
- 虚拟现实-VR-UE4-创建第一个C++项目——Hello word
- 用 Visual C++ 2015 编译 FreeType 2.6.2
- ios开发 int,NSInteger,NSUInteger,NSNumber
- Mybatis全解
- 蓝牙通道
- Oracle中常用sql函数(2)
- Class文件结构
- SQL SERVER2005 复制订阅功能介绍
- Nginx 反向代理
- linux 安装配置 jdk
- httpClient 接口调用
- Linux 文件描述符和文件锁
- 大数据情况下桶排序算法的运用与C++代码实现示例
- 环信web sdk集成注意事项