ES6-Class
2016-06-23 10:17
155 查看
Class
第一次接触的你需要注意哪些地方
类结构体内部的方法定义不能(不需要)使用function字段类名必须大写。好像没有明确规定,但你就当有这个规定吧
类结构体虽然是放在
{}内,但此时的
{}并不表示对象,而表示代码块,所以不要像之前定义prototype一样使用
,分割各个函数
类结构体中的所有方法都会被挂载到prototype对象上,成为各实例的通用方法
同let&const一样,不存在变量提升
不多说,都在demo里了,走一个。。。
new Demo() // 不存在变量提升,这里会报错 class Demo { // 类名大写 constructor(x, y) { // 构造函数。可以不定义构造函数默认`constructor() {}` this.x = x; this.y = y; } // 不需要`,`分割 toString() { // 不需要`function`定义函数 return '(' + this.x + ', ' + this.y + ')'; } }
继承 extends
子类通过构造函数向父类传参super代表父类的构造函数
调用super之后才能使用this关键字,否则会报错
demo
class DemoChild extends Demo{ constructor(...args){ this.args = args; // 报错啦,这里还没有this呢。。 super(...args); this.args = args; //这才对嘛。。 } }
可以继承原生构造函数
class GoodArray extends Array{ // 妈妈再也不用担心对原生构造函数的扩展带来的各种问题 constructor(...args){ super(...args); } toString(){ console.log('I am better then Array'); } } var arr = new GoodArray(); arr.toString();
prototype & __proto__
__proto__总是指向父类prototype的__proto__总是指向父类的prototype
绕死算了^v^
DemoChild.\_\_proto\_\_ === Demo; DemoChild.prototype.\_\_proto\_\_ === Demo.prototype;
getter & setter
class内部可以定义get&set方法,用于存取属性的值。用法和对象属性的getter&setter相同class Demo{ constructor(foo){ this._foo = foo; } get foo(){ console.log('get foo: ' + this._foo); return this._foo; } set foo(val){ this._foo = val; console.log('set foo: ' + this._foo); } } var demo = new Demo(111); demo.foo = 123; // set foo: 123 demo.foo; // get foo: 123
静态方法
static关键字静态方法可以直接通过类名调用,不需要实例化
静态方法不会被实例继承
父类的静态方法可以被子类继承
静态方法也可以通过supper()调用
来个糖炒栗子吧
class Demo{ static hello(){ console.log('hello'); } } class ChildDemo extends Demo{ } var demo = new Demo(); var childDemo = new ChildDemo(); Demo.hello(); // hello ChildDemo.hello(); // hello demo.hello(); // 报错啦 childDemo.hello(); // 根本就没执行到我,其实我也一样报错
静态属性和实例属性
如何定义静态属性?ES6规定Class内部只允许定义静态方法,不允许定义静态属性,ES7中有内部定义静态属性的提案,但是那是ES7的事情了实例属性只能在constructor中定义
class Demo{ constructor(...props){ this.props = props; // 定义实例属性 } } Demo.props = 'static props'; var demo = new Demo(1, 2, 3); console.log(demo.props); // [1, 2, 3] console.log(Demo.props); // 'static props'
相关文章推荐
- (OK) Android adb连接VirtualBox方式
- 浅析Bootstrap验证控件的使用
- linux查看tcp的状态命令:
- LDD
- [codevs1742] 爬楼梯
- 跨域方法总结
- 数据结构之二叉搜索树
- Android上下TabHost设置及Did you forget to call 'public void setup(LocalActivityManager activityGroup)解决方法
- 软件工程个人报告
- C++ const成员函数
- Java、Hibernate(JPA)注解大全
- django模板报错Requested setting TEMPLATE_DEBUG, but...
- Java - Map
- Python基础篇之初识Python必看攻略
- Android 中的 Service 全面总结
- sdut 3468 广度优先搜索练习之神奇的电梯(BFS)
- java 操作给定的二叉树,将其变换为源二叉树的镜像。
- 关于代码解耦
- css px 和 % ,em 等混合计算宽度或者高度
- idea工具的编码问题