ECMAScript6-Class的基本语法

系列文章目录

上一期讲解了对象相关的内容,这一期讲解class的基本语法。



提示:以下是本篇文章正文内容,下面案例可供参考

  • ES6 提供了更接近传统语⾔的写法,引⼊了 Class(类)这个概念,作为对象的模板。通过class关 键字,可以定义类。
  • 基本上,ES6 的class可以看作只是⼀个语法糖,它的绝⼤部分功能,ES5 都可以做到,
  • 新的class写法只是让对象原型的写法更加清晰、更像⾯向对象编程的语法⽽已。
class Point {
 constructor(x, y) {
 this.x = x;
 this.y = y;
 }
 toString() {
 return '(' + this.x + ', ' + this.y + ')';
 }
}
  • constructor⽅法是类的默认⽅法,通过new命令⽣成对象实例时,⾃动调⽤该⽅法。
//定义类
class Point {
 constructor(x, y) {
 this.x = x;
 this.y = y;
 }
 toString() {
 return '(' + this.x + ', ' + this.y + ')';
 }
}
var point = new Point(2, 3);
point.toString() // (2, 3)
  • Class 表达式
  • 与函数⼀样,类也可以使⽤表达式的形式定义。
const MyClass = class Me {
 getClassName() {
 return Me.name;
 }
};
  • 上⾯代码使⽤表达式定义了⼀个类。需要注意的是,这个类的名字是Me,
  • 但是Me只在 Class 的内部可⽤,指代当前类。在 Class 外部,这个类只能⽤MyClass引⽤。
let inst = new MyClass();
inst.getClassName() // Me
Me.name // ReferenceError: Me is not defined
  • 静态⽅法
  • 类相当于实例的原型,所有在类中定义的⽅法,都会被实例继承。
  • 如果在⼀个⽅法前,加上static关键字,就表示该⽅法不会被实例继承,⽽是直接通过类来调⽤,
    这就称为“静态⽅法”。
class Foo {
 static classMethod() {
 return 'hello';
 }
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

总结

本文讲解了class的基本语法,下一期我们讲解class的继承

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值