# 类的由来
- es5,通过构造函数去实例化对象
 
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);
- es6 ES6 的 class 可以看作只是一个语法糖
 
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}
//可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。
- prototype 属性 构造函数的 prototype 属性,在 ES6 的“类”上面继续存在。事实上,类的所有方法都定义在类的 prototype 属性上面
 
class Point {
  constructor() {
    // ...
  }
  toString() {
    // ...
  }
  toValue() {
    // ...
  }
}
// 等同于
Point.prototype = {
  constructor() {},
  toString() {},
  toValue() {},
};
- proto属性 与 ES5 一样,类的所有实例共享一个原型对象。
 
var p1 = new Point(2, 3);
var p2 = new Point(3, 2);
p1.__proto__ === p2.__proto__;
- 类不存在变量提升
 
new Foo(); // ReferenceError
class Foo {}
- 静态方法
 
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
← async函数 generate函数 →