ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
语法
class Father{
constructor(){ // 构造函数
this.a = '12'; // this实例对象
}
toString(){
cosole.log('hah');
}
}
console.log(typeof Father);//"function"
console.log(Father===Father.prototype.constructor);//true
- 相当于是构造函数
- 类内所有的方法都是挂在
prototype
上,且不可枚举
Object.hasOwnPropertyNames(Point.prototype)
返回一个指定对象的所有自身属性的属性名(包括不可枚举属性,但是不包括名为Symbol的属性)组成的数组。 constructor
默认返回实例对象,如果没有显式写,引擎也会默认为其加上constructor
函数- 可以使用
get
取值函数和set
存值函数(都是挂在Descriptor
对象上的)
class Father{
constructor(){
this.a = '12';
}
get prop(){
return 'hah';
}
set prop(value){
console.log("Fail", value);
}
toString(){
cosole.log('hah');
}
}
let oL = new Father();
oL.prop = 123; //Fail 123
console.log(oL.prop); //hah
使用时需要注意
-
内部使用严格模式,不存在变量提升
-
this
指向问题,类内部方法的this
是指向实例的,如果单独使用this
,会导致this
指向运行环境,但使用的是严格模式,所以是undefined
,从而找不到方法报错。- 解决办法
1.在构造函数中绑定this
2.使用箭头函数
- 解决办法
// printName方法中的this,默认指向Logger类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境(由于 class 内部是严格模式,所以 this 实际指向的是undefined),从而导致找不到print方法而报错。
class Logger {
printName(name = 'there') {
this.print(`Hello ${name}`);
}
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined
// 解决方案1 手动绑定this
class Logger {
constructor() {
this.printName = this.printName.bind(this);
}
printName(name = 'there') {
this.print(`Hello ${name}`);
}
print(text) {
console.log(text);
}
}
// 解决方案2 箭头函数
class Obj {
constructor() {
this.getThis = () => this;
}
}
const myObj = new Obj();
myObj.getThis() === myObj // true
- 静态方法和静态属性:不会被实例继承,可以通过类直接调用,且在静态方法中的
this
是指向类的,可以被子类(extends
)继承
实例属性
class foo {
bar = 'hello'; // 和写在constructor一样,都是定义在实例对象上的属性
baz = 'world';
constructor() {
// ...
}
}
静态方法和静态属性
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
class Foo {
static classMethod() { // 如果静态方法包含this关键字,这个this指的是类,而不是实例。
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod() // TypeError: foo.classMethod is not a function
私有方法和私有属性
只能在类的内部使用(this.#count)。如果在类的外部使用,就会报错。
class IncreasingCounter {
#count = 0;
get value() {
console.log('Getting the current value!');
return this.#count;
}
increment() {
this.#count++;
}
}
const counter = new IncreasingCounter();
counter.#count // 报错
counter.#count = 42 // 报错
new.target
的使用
- 可以确定构造函数是怎么调用的。
// 实例必须通过new创建
function Person(name) {
if (new.target !== undefined) { // if (new.target === Person) {
this.name = name;
} else {
throw new Error('必须使用 new 命令生成实例');
}
}
- class内部调用,返回当前的class,子类继承父类的时候,new.target返回的是子类
class Rectangle {
constructor(length, width) {
console.log(new.target === Rectangle); // true, 子类继承父类时,new.target会返回子类
this.length = length;
this.width = width;
}
}
// 利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。
class Shape {
constructor() {
if (new.target === Shape) {
throw new Error('本类不能实例化');
}
}
}
class Rectangle extends Shape {
constructor(length, width) {
super();
// ...
}
}
var x = new Shape(); // 报错
var y = new Rectangle(3, 4); // 正确
继承
class Point { /* ... */ }
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y); // 调用父类的constructor(x, y)
this.color = color;
}
toString() {
return this.color + ' ' + super.toString(); // 调用父类的toString()
}
}
为什么一定要在构造函数中调用super()
super在这里表示父类的构造函数,用来新建一个父类的实例对象。如果不调用,则会报错。
原因:这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,添加子类自己的实例属性和方法。如果不调用super()方法,子类就得不到自己的this对象。
- ES5 的继承机制,是先创造一个独立的子类的实例对象,然后再将父类的方法添加到这个对象上面,即“实例在前,继承在后”。
- ES6 的继承机制,则是先将父类的属性和方法,加到一个空的对象上面,然后再将该对象作为子类的实例,即“继承在前,实例在后”。
静态属性和静态方法,私有属性和私有方法
- 父类的私有属性和私有方法,不会被子类继承
- 父类的静态属性和静态方法,也会被子类继承,会进行浅拷贝
class A { static foo = 100; }
class B extends A {
constructor() {
super();
B.foo--;
}
}
const b = new B();
B.foo // 99
A.foo // 100