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下通过测试
- ES6学习——类语法:继承内置的类(如Array,Error等)
- ES6学习——类语法:继承中的原型链
- ES6学习——类语法:继承中的原型链
- ES6学习——新的语法:数组解构(Array Destructuring)
- ES6学习——类语法:继承中的实例构造过程
- ES6学习——类语法:其它
- 9、字符串、数组、对象等内置对象的拓展—ES6学习笔记
- ES6 类的继承
- ES6学习——类语法:基本概念介绍
- ES6学习——类语法:super和new.target
- ES6学习——新的语法:Symbol private类属性
- ES6 —(Class 的继承)
- ES6 —(Class 的基本语法)
- ES6 —(Module 的语法)
- ES6 —(Generator 函数的语法)
- JavaScript ES6新的类继承特性学习笔记
- 7、class的继承—ES6学习笔记
- ES6学习——新的语法:let
- What is virtual memory, how is it implemented, and why do operating systems use it?
- [leetcode] 222. Count Complete Tree Nodes 解题报告
- udig中配置style对于中文标注设置问题
- BZOJ 3211: 花神游历各国 |树状数组|并查集
- clojure on the beginning
- ES6学习——类语法:继承内置的类(如Array,Error等)
- python isinstance(), stack,判断list, dict, tuple为空
- 对Keil MDK 启动代码的理解
- linux(Ubuntu)中安装mavne私服Nexus
- Android 进程生命周期 Process Lifecycle
- LeetCode Remove Invalid Parentheses
- Excel中的Array Formula
- LeetCode Additive Number
- C++的高级用法