Class 类
基本概念
类的所有方法都定义在类的 prototype
属性上面
JS
class Point {
constructor() {
// ...
}
toString() {
// ...
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
};
class Point {
constructor() {
// ...
}
toString() {
// ...
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
};
与 ES5
的 Point.prototype.constructor === Point
一致,因为 constructor
中的 this
就是指向构造函数本身
constructor
constructor
方法是类的默认方法,通过 new
命令生成对象实例时,自动调用该方法。一个类必须有 constructor
方法,如果没有显式定义,一个空的 constructor
方法会被默认添加。
静态属性
有提案,在属性前加 static
关键字
静态方法
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上 static
关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
JS
class Foo {
// 静态方法前需要加 static 关键字,静态方法不会被继承
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
}
class Bar extends Foo {
static classMethod() {
// 从 super 对象上调用
return super.classMethod() + ', too';
}
}
Foo.classMethod() // 'hello'
Bar.classMethod() // 'hello'
class Foo {
// 静态方法前需要加 static 关键字,静态方法不会被继承
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
}
class Bar extends Foo {
static classMethod() {
// 从 super 对象上调用
return super.classMethod() + ', too';
}
}
Foo.classMethod() // 'hello'
Bar.classMethod() // 'hello'
- 父类的静态方法,可以被子类继承。
私有属性与方法
提案阶段,在属性与方法前面加上 #
符号,使用时对该属性或方法也要带上 #