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;

  }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM