系列文章目录
上一期讲解了对象相关的内容,这一期讲解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的继承