Class和普通构造函数的区别

1、JS构造函数

function fn(x, y) {
  this.x = x;

  this.y = y;
}

使用 var a = new fn(1, 2)

使用prototype进行扩展,在fn.prototype上定义的方法,在所有fn的实例中都能使用,如:

  fn.prototype.add = function() {

    return this.x + this.y;

  }

fn.prototype.constructor === fn

a.__proto__ === fn.prototype

2、Class语法(形式上模仿java、c#,却失去了它的本性和个性,class是语法糖)

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

    this.y = y;

  }
  add() {
    return this.x + this.y;

  }
}

 

posted @ 2019-02-18 16:15  原始人活在新时代  阅读(962)  评论(0编辑  收藏  举报