类 是一个语法糖
在ES6中为了让对象的原型的写法更加清新、更像是面向对象编程的语法。引入了class
关键词
constructor 构造方法(默认方法)
class Person{
constructor(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}
这里的 this
关键字代表实例对象。通过new
命令生成对象实例时,自动调用该方法。一个类必须有constructor()
方法,如果没有显式定义,一个空的constructor()
方法会被默认添加。
toString 自定义方法
class Person{
constructor(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;
}
toString(){
return this.firstName + this.lastName;
}
}
toString
方法的前面不需要加 function
关键字。
取值函数 getters 和 存值函数 setter
class Person{
constructor(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;
}
get prop(){
return 'getter';
}
set prop(value){
console.log('setter:' + value);
}
}
let person = new Person;
person.prop = 121;
// setter: 121;
person.prop
// 'getter'
Gennerator 方法
如果某个方法之前加上星号(*
),就表示该方法是一个 Generator 函数。
class Foo {
constructor(...args) {
this.args = args;
}
* [Symbol.iterator]() {
for (let arg of this.args) {
yield arg;
}
}
}
for (let x of new Foo('hello', 'world')) {
console.log(x);
}
// hello
// world
name 属性
由于类的本质是ES5的构造函数的一种包装,所以函数的许多特性都是被 Class
继承,其中包含 name
属性
class Person{
constructor(){
//...
}
}
Person.name // 'Person'
name
属性总是返回紧跟在class
关键字后面的类名。
Class 类 Tips:
- 方法与方法之间不需要逗号分隔,加了会报错。
- 类内部定义的方法,它是不可枚举的。
- 类的方法内部如果含有
this
,它默认指向类的实例。如果将类中的方法提取出来单独使用,this
会指向该方法运行时所在的环境。
参考文献
阮一峰老师的 ECMAScript 6 入门
点赞 评论 收藏 ~~ 今天的学习记录暂时到这。 ~~ 点赞 评论 收藏