1、ES6提供了更接近傳統語言的寫法,引入了Class(類)這個概念,作為對象的模板。通過class
關鍵字,可以定義類。
2、
//定義類 class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; } }
上面代碼定義了一個“類”,可以看到里面有一個constructor
方法,這就是構造方法,而this
關鍵字則代表實例對象。也就是說,ES5的構造函數Point
,對應ES6的Point
類的構造方法。
3、定義“類”的方法的時候,前面不需要加上function
這個關鍵字,直接把函數定義放進去了就可以了。另外,方法之間不需要逗號分隔,加了會報錯。
4、構造函數的prototype
屬性,在ES6的“類”上面繼續存在。事實上,類的所有方法都定義在類的prototype
屬性上面。
class Point { constructor(){ // ... } toString(){ // ... } toValue(){ // ... } } // 等同於 Point.prototype = { toString(){}, toValue(){} };
5、Object.assign
方法可以很方便地一次向類添加多個方法。
class Point { constructor(){ // ... } } Object.assign(Point.prototype, { toString(){}, toValue(){} });
6、類的內部所有定義的方法,都是不可枚舉的(non-enumerable)。這一點與ES5的行為不一致。
7、類的屬性名,可以采用表達式。
let methodName = "getArea"; class Square{ constructor(length) { // ... } [methodName]() { // ... } }
上面代碼中,Square
類的方法名getArea
,是從表達式得到的。
8、constructor
方法是類的默認方法,通過new
命令生成對象實例時,自動調用該方法。一個類必須有constructor
方法,如果沒有顯式定義,一個空的constructor
方法會被默認添加。constructor
方法默認返回實例對象(即this
),完全可以指定返回另外一個對象。
9、類的構造函數,不使用new
是沒法調用的,會報錯。
10、可以通過實例的__proto__
屬性為Class添加方法。
var p1 = new Point(2,3); var p2 = new Point(3,2); p1.__proto__.printName = function () { return 'Oops' }; p1.printName() // "Oops" p2.printName() // "Oops" var p3 = new Point(4,2); p3.printName() // "Oops"
11、使用實例的__proto__
屬性改寫原型,必須相當謹慎,不推薦使用,因為這會改變Class的原始定義,影響到所有實例。
12、Class不存在變量提升(hoist)。