You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classFoo{constructor(){returnObject.create(null);}}Foo()// TypeError: Class constructor Foo cannot be invoked without 'new'
class必须使用 new 调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用 new 也可以执行
注意点
类和模块内部,默认就是严格模式
类不存在变量提升
newFoo();// ReferenceErrorclassFoo{}
name 属性返回 class 关健字后面的类名
classPoint{}Point.name// "Point"
如果某个方法之前加上星号(*),就表示该方法是一个 Generator 函数
classFoo{constructor(...args){this.args=args;}*[Symbol.iterator](){for(letargofthis.args){yieldarg;}}}for(letxofnewFoo('hello','world')){console.log(x);}// hello// world
总结
基本用法
this 关键字代表实例对象
constructor为构造方法, 通过 new 命令生成实例时自动被调用, 没有显式定义时一个空的 constructor 会被默认添加, constructor 方法默认返回实例对象(即this)
ES6总结系列之 class(上) 篇
1.何为class
class
完全可以看作构造函数的另一种写法,使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致class
也可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已2.基本用法
我们先来看一个例子
this
关键字代表实例对象constructor
为构造方法, 通过new
命令生成实例时自动被调用, 没有显式定义时一个空的constructor
会被默认添加,constructor
方法默认返回实例对象(即this)定义类方法不需要关键字
function
方法之间不需要逗号分隔,加了会报错
类的所有方法都定义在类的
prototype
属性上面prototype
对象的constructor
属性,直接指向“类”的本身,这与 ES5 的行为是一致的class
必须使用new
调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用 new 也可以执行注意点
总结
基本用法
this
关键字代表实例对象constructor
为构造方法, 通过new
命令生成实例时自动被调用, 没有显式定义时一个空的constructor
会被默认添加,constructor
方法默认返回实例对象(即this)function
prototype
属性上面prototype
对象的constructor
属性,直接指向“类”的本身,这与 ES5 的行为是一致的class
必须使用new
调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用 new 也可以执行注意要点
__
欢迎star,持续更新ing...
ES6总结系列参考自阮一峰《ES6入门教程》
The text was updated successfully, but these errors were encountered: