ES6学习——类语法:继承内置的类(如Array,Error等)

来源:互联网 发布:提高口才知乎 编辑:程序博客网 时间:2024/06/09 22:05

ES6的规范中在介绍内置类时,明确说明了哪些内置类可以subclass,没有说的自然不行。

我们看几个内置类的描述:


The Error constructor is designed to be subclassable. It may be used as the value of an extends clause of a class definition. Subclass constructors that intend to inherit the specified Error behaviour must include a super call to the Error constructor to create and initialize subclass instances with a [[ErrorData]] internal slot.


The Array constructor is designed to be subclassable. It may be used as the value of an extends clause of a class definition. Subclass constructors that intend to inherit the exotic Array behaviour must include a super call to the Array constructor to initialize subclass instances that are exotic Array objects.


不再列举了,以前由于Error类不能subclass,所以不能抛出自定义的Error,在ES6中已经可以了。注意这个特性需要浏览器的原生支持,无法用ES6 transpilers实现。

看个数组的例子:

class MyArray extends Array {constructor(len) {super(len);}sum(){return this.reduce(function(prevVal,curVal){return prevVal + curVal},0);}}var arr = new MyArray(3);console.log(typeof MyArray,arr instanceof MyArray,arr instanceof Array);//function true trueconsole.log(arr.length);//3arr[0] = 1;arr[4] = 2;console.log(arr.length,arr);//5 [1,,,,2]console.log(arr.sum());//3

下面在看一个Error的例子:

class RuntimeError extends Error{constructor(desc,funcName) {super(desc);this.funcName = funcName;}toString(){return this.funcName + "->" + this.message}}function test(){throw new RuntimeError("oh~","test");}try{test();}catch(e){console.error(e.toString());//test->oh~}

看了这两个例子是不是觉得JS也开始OO了起来,顿时高大上了。


*以上全部代码在Chrome 47下通过测试



0 0