js class和构造函数的区别

其实JS一直有一个关键字(保留字):class,只不过一直没正式使用,直到ES6。

ES6的class就是取代之前构造函数初始化对象的形式,从语法上更符合面向对象的写法。

面向对象

我们来看下,JS 构造函数的写法:

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

MathHandle.prototype.add = function () {
  return this.x + this.y;
};

var m = new MathHandle(1, 2);
console.log(m.add())

用 ES6 class 的写法:

class MathHandle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  add() {
    return this.x + this.y;
  }
}
const m = new MathHandle(1, 2);
console.log(m.add())

我们对比一下不难发现,构造函数函数体的内容要放在class的constructor函数中,constructor即构造器,初始化实例时默认执行。

class中函数的写法是 add() {….} 这种形式,并没有function关键字。