ES6 類(class)
js語言的傳統方式是通過定義構造函數,生成心得對象。是一種基於原型的面向對象系統。在es6中增加了class類的概念,可以使用class關鍵字來聲明一個類。之后用這個類來實例化對象。
構造函數示例
const Demo = function(a,b){ this.a = a; this.b = b; return this; } Demo.prototype = { constructor: Demo, print: function(){ console.log(this.a+this.b); } } const demo = new Demo('jane','yun').print();
class Demo { constructor(a,b){ this.a = a; this.b = b; return this; } print(){ console.log(this.a+this.b); } } const demo = new Demo('hello','world').print();
Demo中的constructor是構造方法,this關鍵字代表示例對象。
注:定義類的方法的時候不需要寫function,另外 也不需要逗號。
2:靜態方法
class Point{ constructor(a,b){ this.a = a; this.b = b; return this; } static print(){ console.log('say hi'); } } const Point.print();
3:繼承
class A{ constructor(a){ this.a = a; return this; } string(){ return 'hello,'+ this.a } } class B extends A{ constructor(a){ super(); } m(){ super.sting(); } } const b = new B(3);
super
1、super作為函數調用時,代表父類的構造函數。ES6 要求,子類的構造函數必須執行一次super函數。
2、super作為對象時,在普通方法中,指向父類的原型對象;在靜態方法中,指向父類
super代表了父類A的構造函數,但是返回的是子類B的實例,即super內部的this指的是B,因此super()在這里相當於A.prototype.constructor.call(this)。