1. 程式人生 > >es6 class

es6 class

function 執行 ret asc 必須 清晰 one 編程 語法

ES6的class可以看作只是一個語法糖,它的絕大部分功能,ES5都可以做到,新的class寫法只是讓對象原型的寫法更加清晰、更像面向對象編程的語法而已。

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

Point.prototype.toString = function () {
  return ‘(‘ + this.x + ‘, ‘ + this.y + ‘)‘;
};
等同於

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

  toString() {
    
return ‘(‘ + this.x + ‘, ‘ + this.y + ‘)‘; } }

在 JavaScript 中,每個對象都有原型對象。所有 JavaScript 對象都從原型上繼承方法和屬性。
ES5中,屬性放在構造函數(constructor)裏,方法放在原型(prototype)上;
ES6中引入了類(class)來代替構造函數(constructor);

在之類的constructor中必須調用 super方法,子類沒有自己的this對象,而是繼承父類的this對象,然後對其進行加工。super代表了父類構造函數。對於你的實例相當於執行Component(props)。但是註意,此處this指向 子類。更嚴謹的是相當於

Component.prototype.constructor.call(this,props)。

至於為什麽一定要有super?可以很容易想得到,先有父才有子嘛。super繼承父類屬性,在constructor中進行自己的改造。如果在constructor中使用到this,必須在使用this之前調用super()。

es6 class