ES6 ECMAScript 2015或ES2015是对JavaScript编程语言的重大更新。这是自2009年对ES5进行标准化以来对语言的首次重大更新,ES6加入很多有用的特性。因此,ES2015通常被称为ES6。
本文环境:
NodeJs版本:v12.13.0
OS:Ubuntu 18.04.4 LTS
class语法糖 首先我们先来看一下关于 ES6 中的类
1 2 3 4 5 class Persion { say() { console .log('hello~' ) } }
上面这段代码是 ES6 中定义一个类的写法,其实只是一个语法糖,而实际上当我们给一个类添加一个属性的时候,会调用到 Object.defineProperty
这个方法,它会接受三个参数:target 、name 和 descriptor ,所以上面的代码实际上在执行时是这样的:
1 2 3 4 5 6 7 8 function Persion ( ) {}Object .defineProperty(Persion.prototype, "say" , { value: function ( ) { console .log("hello ~" ); }, enumerable: false , configurable: true , writable: true });
ES6中extends ES6中可以很方便地用extends
的实现继承:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Shape { constructor (x, y) { this .x = x; this .y = y; } move(x, y) { this .x += x; this .y += y; console .info('Shape moved.' ); } } class Rectangle extends Shape { constructor () { super (); } }
要用ES5实现继承,就是用利用原型链 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 function Shape ( ) { this .x = 0 ; this .y = 0 ; } Shape.prototype.move = function (x, y ) { this .x += x; this .y += y; console .info('Shape moved.' ); }; function Rectangle ( ) { Shape.call(this ); } Rectangle.prototype = Object .create(Shape.prototype); Rectangle.prototype.constructor = Rectangle; var rect = new Rectangle();console .log('Is rect an instance of Rectangle?' , rect instanceof Rectangle); console .log('Is rect an instance of Shape?' , rect instanceof Shape); rect.move(1 , 1 );
参考: