ES6 class 类的概念

类 是一个语法糖

在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 入门


点赞 评论 收藏 ~~ 今天的学习记录暂时到这。 ~~ 点赞 评论 收藏
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shaoin_2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值