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