【ES6】阮一峰ES6学习之Class(一)

1. 类的由来

JavaScript 语言中,生成实例对象的传统方法是通过构造函数。

function Point(x, y) {
    
    
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function () {
    
    
  return '(' + this.x + ', ' + this.y + ')';
};

var p = new Point(1, 2);

上面这种写法跟传统的面向对象语言(比如 C++ 和 Java)差异很大,很容易让新学习这门语言的程序员感到困惑。

ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。

基本上,ES6 的 class 可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。

把上面例子用 ES6 改写一下

class Point {
    
    
	constructor(x, y){
    
    
		this.x = x;
		this.y = y;
	}
	toString() {
    
    
		return '(' + this.x + ', ' + this.y + ')';
	}
}

ES6 的类,完全可以看作构造函数的另一种写法。

// 类的数据类型就是函数,类本身就指向构造函数。
class Point {
    
    
  // ...
}

typeof Point // "function"
Point === Point.prototype.constructor // true

使用的时候,也是直接对类使用new命令,和构造函数的用法完全一致。

class Bar {
    
    
    doSomething(){
    
    
        console.log('something');
    }
}

const b = new Bar();
b.doSomething();   // something

构造函数的prototype属性,在 ES6 的“类”上面继续存在。事实上,类的所有方法都定义在类的prototype属性上面。

class Point {
    
    
  constructor() {
    
    
    // ...
  }

  toString() {
    
    
    // ...
  }

  toValue() {
    
    
    // ...
  }
}

// 等同于

Point.prototype = {
    
    
  constructor() {
    
    },
  toString() {
    
    },
  toValue() {
    
    },
};

上面代码中,constructor()、toString()、toValue()这三个方法,其实都是定义在Point.prototype上面。

在类的实例上面调用方法,其实就是调用原型上的方法。

// b是B类的实例,它的constructor()方法就是B类原型的constructor()方法。
class B {
    
    }
const b = new B();

b.constructor === B.prototype.constructor // true

prototype对象的constructor属性,直接指向“类”的本身,这与 ES5 的行为是一致的。

Point.prototype.constructor === Point // true

注意:类的内部所有定义的方法,都是不可枚举的(non-enumerable)。

class Point {
    
    
  constructor(x, y) {
    
    
    // ...
  }

  toString() {
    
    
    // ...
  }
}

Object.keys(Point.prototype)
// []
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]

代码采用 ES5 的写法,toString()方法就是可枚举的。

var Point = function (x, y) {
    
    
  // ...
};

Point.prototype.toString = function () {
    
    
  // ...
};

Object.keys(Point.prototype)
// ["toString"]
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]

2. constructor() 方法

constructor()方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor()方法,如果没有显式定义,一个空的constructor()方法会被默认添加。

class Point {
    
    
}

// 等同于
class Point {
    
    
  constructor() {
    
    }
}

上面代码中,定义了一个空的类Point,JavaScript 引擎会自动为它添加一个空的constructor()方法。

constructor()方法默认返回实例对象(即this),完全可以指定返回另外一个对象。

class Foo {
    
    
  constructor() {
    
    
    return Object.create(null);
  }
}

new Foo() instanceof Foo
// false

上面代码中,constructor()函数返回一个全新的对象,结果导致实例对象不是Foo类的实例。

类必须使用new调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用new也可以执行。

class Foo {
    
    
  constructor() {
    
    
    return Object.create(null);
  }
}

Foo()
// TypeError: Class constructor Foo cannot be invoked without 'new'

3. 类的实例

new一下

类的属性和方法,除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。

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)

point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true

上面代码中,x和y都是实例对象point自身的属性(因为定义在this对象上),所以hasOwnProperty()方法返回true,而toString()是原型对象的属性(因为定义在Point类上),所以hasOwnProperty()方法返回false。这些都与 ES5 的行为保持一致。

与 ES5 一样,类的所有实例共享一个原型对象。

var p1 = new Point(2,3);
var p2 = new Point(3,2);

p1.__proto__ === p2.__proto__
//true

p1p2都是Point的实例,它们的原型都是Point.prototype,所以__proto__属性是相等的。

4. 取值函数(getter)和存值函数(setter)

与 ES5 一样,在“类”的内部可以使用getset关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。

class MyClass {
    
    
  constructor() {
    
    
    // ...
  }
  get prop() {
    
    
    return 'getter';
  }
  set prop(value) {
    
    
    console.log('setter: '+value);
  }
}

let inst = new MyClass();

inst.prop = 123;
// setter: 123

inst.prop
// 'getter'

上面代码中,prop属性有对应的存值函数和取值函数,因此赋值和读取行为都被自定义了。

存值函数和取值函数是设置在属性的 Descriptor 对象上的。

class CustomHTMLElement {
    
    
  constructor(element) {
    
    
    this.element = element;
  }

  get html() {
    
    
    return this.element.innerHTML;
  }

  set html(value) {
    
    
    this.element.innerHTML = value;
  }
}

var descriptor = Object.getOwnPropertyDescriptor(
  CustomHTMLElement.prototype, "html"
);

"get" in descriptor  // true
"set" in descriptor  // true

上面代码中,存值函数和取值函数是定义在html属性的描述对象上面,这与 ES5 完全一致。

5. 静态方法

静态方法: 类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

class Foo {
    
    
  static classMethod() {
    
    
    return 'hello';
  }
}

Foo.classMethod() // 'hello'

var foo = new Foo();
foo.classMethod(); // TypeError: foo.classMethod is not a function

注意,如果静态方法包含this关键字,这个this指的是类,而不是实例。

class Foo {
    
    
  static bar() {
    
    
    this.baz();
  }
  static baz() {
    
    
    console.log('hello');
  }
  baz() {
    
    
    console.log('world');
  }
}

Foo.bar() // hello

上面代码中,静态方法bar调用了this.baz,这里的this指的是Foo类,而不是Foo的实例,等同于调用Foo.baz。另外,从这个例子还可以看出,静态方法可以与非静态方法重名。

6. 私有方法和私有属性

私有方法和私有属性,是只能在类的内部访问的方法和属性,外部不能访问。

ES2022正式为class添加了私有属性,方法是在属性名之前使用#表示。

class IncreasingCounter {
    
    
  #count = 0;
  get value() {
    
    
    console.log('Getting the current value!');
    return this.#count;
  }
  increment() {
    
    
    this.#count++;
  }
}
// #count就是私有属性,只能在类的内部使用(this.#count)。如果在类的外部使用,就会报错。
const counter = new IncreasingCounter();
counter.#count // 报错
counter.#count = 42 // 报错

7. 类的注意点

1. 严格模式

类和模块的内部,默认就是严格模式,所以不需要使用use strict指定运行模式。只要你的代码写在类或模块之中,就只有严格模式可用。考虑到未来所有的代码,其实都是运行在模块之中,所以 ES6 实际上把整个语言升级到了严格模式。

2. 不存在变量提升

类不存在变量提升(hoist),这一点与 ES5 完全不同。

new Foo(); // ReferenceError
class Foo {
    
    }

上面代码中,Foo类使用在前,定义在后,这样会报错,因为 ES6 不会把类的声明提升到代码头部。这种规定的原因与下文要提到的继承有关,必须保证子类在父类之后定义。

{
    
    
  let Foo = class {
    
    };
  class Bar extends Foo {
    
    
  }
}

上面的代码不会报错,因为Bar继承Foo的时候,Foo已经有定义了。但是,如果存在class的提升,上面代码就会报错,因为class会被提升到代码头部,而let命令是不提升的,所以导致Bar继承Foo的时候,Foo还没有定义。

3. Generator 方法

如果某个方法之前加上星号(*),就表示该方法是一个 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

上面代码中,Foo类的Symbol.iterator方法前有一个星号,表示该方法是一个 Generator 函数。Symbol.iterator方法返回一个Foo类的默认遍历器,for…of循环会自动调用这个遍历器。

4. this指向

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

printName方法中的this,默认指向Logger类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境(由于class内部是严格模式,所以 this 实际指向的是undefined),从而导致找不到print方法而报错。

一个比较简单的解决方法是,在构造方法中绑定this,这样就不会找不到print方法了。

class Logger {
    
    
  constructor() {
    
    
    this.printName = this.printName.bind(this);
  }

  // ...
}

另一种解决方法是使用箭头函数。

class Obj {
    
    
  constructor() {
    
    
    this.getThis = () => this;
  }
}

const myObj = new Obj();
myObj.getThis() === myObj // true

猜你喜欢

转载自blog.csdn.net/Bon_nenul/article/details/128238488