類和模塊的內部,默認就是嚴格模式,因此不須要使用
use strict
指定運行模式。只要你的代碼寫在類或模塊之中,就只有嚴格模式可用。html考慮到將來全部的代碼,其實都是運行在模塊之中,因此 ES6 實際上把整個語言升級到了嚴格模式。git
題圖:by Frank from Instagram程序員
1、Class的基本語法github
1.1 基本語法編程
JavaScript 語言中,生成實例對象的傳統方法是經過構造函數。下面是一個例子。瀏覽器
1 function Point(x, y) { 2 this.x = x; 3 this.y = y; 4 } 5 Point.prototype.toString = function () { 6 return '(' + this.x + ', ' + this.y + ')'; 7 }; 8 9 var p = new Point(1, 2);
上面這種寫法跟傳統的面嚮對象語言(好比 C++ 和 Java)差別很大,很容易讓新學習這門語言的程序員感到困惑。ide
ES6 提供了更接近傳統語言的寫法,引入了 Class(類)這個概念,做爲對象的模板。經過class
關鍵字,能夠定義類。函數
基本上,ES6 的class
能夠看做只是一個語法糖,它的絕大部分功能,ES5 均可以作到,新的class
寫法只是讓對象原型的寫法更加清晰、更像面向對象編程的語法而已。上面的代碼用 ES6 的class
改寫,就是下面這樣。學習
1 //定義類 2 class Point { 3 constructor(x, y) { 4 this.x = x; 5 this.y = y; 6 } 7 toString() { 8 return '(' + this.x + ', ' + this.y + ')'; 9 } 10 }
上面代碼定義了一個「類」,能夠看到裏面有一個constructor
方法,這就是構造方法,而this
關鍵字則表明實例對象。也就是說,ES5 的構造函數Point
,對應 ES6 的Point
類的構造方法。this
Point
類除了構造方法,還定義了一個toString
方法。注意,定義「類」的方法的時候,前面不須要加上function
這個關鍵字,直接把函數定義放進去了就能夠了。另外,方法之間不須要逗號分隔,加了會報錯。ES6 的類,徹底能夠看做構造函數的另外一種寫法。
1 class Point { 2 // ... 3 } 4 5 typeof Point // "function" 6 Point === Point.prototype.constructor // true
上面代碼代表,類的數據類型就是函數,類自己就指向構造函數。
使用的時候,也是直接對類使用new
命令,跟構造函數的用法徹底一致。
1 class Bar { 2 doStuff() { 3 console.log('stuff'); 4 } 5 } 6 7 var b = new Bar(); 8 b.doStuff() // "stuff"
構造函數的prototype
屬性,在 ES6 的「類」上面繼續存在。事實上,類的全部方法都定義在類的prototype
屬性上面。
1 class Point { 2 constructor() { 3 // ... 4 } 5 toString() { 6 // ... 7 } 8 toValue() { 9 // ... 10 } 11 } 12 13 // 等同於 14 Point.prototype = { 15 constructor() {}, 16 toString() {}, 17 toValue() {}, 18 };
在類的實例上面調用方法,其實就是調用原型上的方法。
class B {} let b = new B(); b.constructor === B.prototype.constructor // true
上面代碼中,b
是B
類的實例,它的constructor
方法就是B
類原型的constructor
方法。
因爲類的方法都定義在prototype
對象上面,因此類的新方法能夠添加在prototype
對象上面。Object.assign
方法能夠很方便地一次向類添加多個方法。
class Point { constructor(){ // ... } } Object.assign(Point.prototype, { toString(){}, toValue(){} });
prototype
對象的constructor
屬性,直接指向「類」的自己,這與 ES5 的行爲是一致的。
Point.prototype.constructor === Point // true
另外,類的內部全部定義的方法,都是不可枚舉的(non-enumerable)。
class Point { constructor(x, y) { // ... } toString() { // ... } } Object.keys(Point.prototype) // [] Object.getOwnPropertyNames(Point.prototype) // ["constructor","toString"]
上面代碼中,toString
方法是Point
類內部定義的方法,它是不可枚舉的。這一點與 ES5 的行爲不一致。
var Point = function (x, y) { // ... }; Point.prototype.toString = function() { // ... }; Object.keys(Point.prototype) // ["toString"] Object.getOwnPropertyNames(Point.prototype) // ["constructor","toString"]
上面代碼採用 ES5 的寫法,toString
方法就是可枚舉的。
類的屬性名,能夠採用表達式。
1 let methodName = 'getArea'; 2 3 class Square { 4 constructor(length) { 5 // ... 6 } 7 8 [methodName]() { 9 // ... 10 } 11 }
上面代碼中,Square
類的方法名getArea
,是從表達式獲得的。
1.2 constructor 方法
constructor
方法是類的默認方法,經過new
命令生成對象實例時,自動調用該方法。一個類必須有constructor
方法,若是沒有顯式定義,一個空的constructor
方法會被默認添加。
class Point { } // 等同於 class Point { constructor() {} }
上面代碼中,定義了一個空的類Point
,JavaScript 引擎會自動爲它添加一個空的constructor
方法。
constructor
方法默認返回實例對象(即this
),徹底能夠指定返回另一個對象。
1 class Foo { 2 constructor() { 3 return Object.create(null); 4 } 5 } 6 7 new Foo() instanceof Foo 8 // false
上面代碼中,constructor
函數返回一個全新的對象,結果致使實例對象不是Foo
類的實例。
類必須使用new
調用,不然會報錯。這是它跟普通構造函數的一個主要區別,後者不用new
也能夠執行。
1 class Foo { 2 constructor() { 3 return Object.create(null); 4 } 5 } 6 7 Foo() 8 // TypeError: Class constructor Foo cannot be invoked without 'new'
1.3 類的實例對象
生成類的實例對象的寫法,與 ES5 徹底同樣,也是使用new
命令。前面說過,若是忘記加上new
,像函數那樣調用Class
,將會報錯。
class Point { // ... } // 報錯 var point = Point(2, 3); // 正確 var point = new Point(2, 3);
與 ES5 同樣,實例的屬性除非顯式定義在其自己(即定義在this
對象上),不然都是定義在原型上(即定義在class
上)。
1 //定義類 2 class Point { 3 4 constructor(x, y) { 5 this.x = x; 6 this.y = y; 7 } 8 9 toString() { 10 return '(' + this.x + ', ' + this.y + ')'; 11 } 12 13 } 14 15 var point = new Point(2, 3); 16 17 point.toString() // (2, 3) 18 19 point.hasOwnProperty('x') // true 20 point.hasOwnProperty('y') // true 21 point.hasOwnProperty('toString') // false 22 point.__proto__.hasOwnProperty('toString') // true
上面代碼中,x
和y
都是實例對象point
自身的屬性(由於定義在this
變量上),因此hasOwnProperty
方法返回true
,而toString
是原型對象的屬性(由於定義在Point
類上),因此hasOwnProperty
方法返回false
。這些都與 ES5 的行爲保持一致。
與 ES5 同樣,類的全部實例共享一個原型對象。
var p1 = new Point(2,3); var p2 = new Point(3,2); p1.__proto__ === p2.__proto__ //true
上面代碼中,p1
和p2
都是Point
的實例,它們的原型都是Point.prototype
,因此__proto__
屬性是相等的。
這也意味着,能夠經過實例的__proto__
屬性爲「類」添加方法。
__proto__
並非語言自己的特性,這是各大廠商具體實現時添加的私有屬性,雖然目前不少現代瀏覽器的 JS 引擎中都提供了這個私有屬性,但依舊不建議在生產中使用該屬性,避免對環境產生依賴。生產環境中,咱們可使用 Object.getPrototypeOf
方法來獲取實例對象的原型,而後再來爲原型添加方法/屬性。
1 var p1 = new Point(2,3); 2 var p2 = new Point(3,2); 3 4 p1.__proto__.printName = function () { return 'Oops' }; 5 6 p1.printName() // "Oops" 7 p2.printName() // "Oops" 8 9 var p3 = new Point(4,2); 10 p3.printName() // "Oops"
上面代碼在p1
的原型上添加了一個printName
方法,因爲p1
的原型就是p2
的原型,所以p2
也能夠調用這個方法。並且,此後新建的實例p3
也能夠調用這個方法。這意味着,使用實例的__proto__
屬性改寫原型,必須至關謹慎,不推薦使用,由於這會改變「類」的原始定義,影響到全部實例。
1.4 Class 表達式
與函數同樣,類也可使用表達式的形式定義。
1 const MyClass = class Me { 2 getClassName() { 3 return Me.name; 4 } 5 };
上面代碼使用表達式定義了一個類。須要注意的是,這個類的名字是MyClass
而不是Me
,Me
只在 Class 的內部代碼可用,指代當前類。
1 let inst = new MyClass(); 2 inst.getClassName() // Me 3 Me.name // ReferenceError: Me is not defined
上面代碼表示,Me
只在 Class 內部有定義。
若是類的內部沒用到的話,能夠省略Me
,也就是能夠寫成下面的形式。
const MyClass = class { /* ... */ };
採用 Class 表達式,能夠寫出當即執行的 Class。代碼中,person
是一個當即執行的類的實例。
1 let person = new class { 2 constructor(name) { 3 this.name = name; 4 } 5 6 sayName() { 7 console.log(this.name); 8 } 9 }('張三'); 10 11 person.sayName(); // "張三"
1.5 不存在變量提高
類不存在變量提高(hoist),這一點與 ES5 徹底不一樣。
new Foo(); // ReferenceError class Foo {}
上面代碼中,Foo
類使用在前,定義在後,這樣會報錯,由於 ES6 不會把類的聲明提高到代碼頭部。這種規定的緣由與下文要提到的繼承有關,必須保證子類在父類以後定義。
1 { 2 let Foo = class {}; 3 class Bar extends Foo { 4 } 5 }
上面的代碼不會報錯,由於Bar
繼承Foo
的時候,Foo
已經有定義了。可是,若是存在class
的提高,上面代碼就會報錯,由於class
會被提高到代碼頭部,而let
命令是不提高的,因此致使Bar
繼承Foo
的時候,Foo
尚未定義。
1.6 私有方法 和 私有屬性
私有方法:
私有方法是常見需求,但 ES6 不提供,只能經過變通方法模擬實現。
一種作法是在命名上加以區別:
class Widget { // 公有方法 foo (baz) { this._bar(baz); } // 私有方法 _bar(baz) { return this.snaf = baz; } // ... }
上面代碼中,_bar
方法前面的下劃線,表示這是一個只限於內部使用的私有方法。可是,這種命名是不保險的,在類的外部,仍是能夠調用到這個方法。
另外一種方法就是索性將私有方法移出模塊,由於模塊內部的全部方法都是對外可見的。
class Widget { foo (baz) { bar.call(this, baz); } // ... } function bar(baz) { return this.snaf = baz; }
上面代碼中,foo
是公有方法,內部調用了bar.call(this, baz)
。這使得bar
實際上成爲了當前模塊的私有方法。
還有一種方法是利用Symbol
值的惟一性,將私有方法的名字命名爲一個Symbol
值。
1 const bar = Symbol('bar'); 2 const snaf = Symbol('snaf'); 3 4 export default class myClass{ 5 6 // 公有方法 7 foo(baz) { 8 this[bar](baz); 9 } 10 11 // 私有方法 12 [bar](baz) { 13 return this[snaf] = baz; 14 } 15 16 // ... 17 };
上面代碼中,bar
和snaf
都是Symbol
值,致使第三方沒法獲取到它們,所以達到了私有方法和私有屬性的效果。
1.7 ps: 私有屬性的提案
與私有方法同樣,ES6 不支持私有屬性。目前,有一個提案,爲class
加了私有屬性。方法是在屬性名以前,使用#
表示。
1 class Point { 2 #x; 3 4 constructor(x = 0) { 5 #x = +x; // 寫成 this.#x 亦可 6 } 7 8 get x() { return #x } 9 set x(value) { #x = +value } 10 }
上面代碼中,#x
就表示私有屬性x
,在Point
類以外是讀取不到這個屬性的。還能夠看到,私有屬性與實例的屬性是能夠同名的(好比,#x
與get x()
)。
私有屬性能夠指定初始值,在構造函數執行時進行初始化。
class Point { #x = 0; constructor() { #x; // 0 } }
之因此要引入一個新的前綴#
表示私有屬性,而沒有采用private
關鍵字,是由於 JavaScript 是一門動態語言,使用獨立的符號彷佛是惟一的可靠方法,可以準確地區分一種屬性是否爲私有屬性。另外,Ruby 語言使用@
表示私有屬性,ES6 沒有用這個符號而使用#
,是由於@
已經被留給了 Decorator。
該提案只規定了私有屬性的寫法。可是,很天然地,它也能夠用來寫私有方法。
1 class Foo { 2 #a; 3 #b; 4 #sum() { return #a + #b; } 5 printSum() { console.log(#sum()); } 6 constructor(a, b) { #a = a; #b = b; } 7 }
上面代碼中,#sum()
就是一個私有方法。
另外,私有屬性也能夠設置 getter 和 setter 方法。
class Counter { #xValue = 0; get #x() { return #xValue; } set #x(value) { this.#xValue = value; } constructor() { super(); // ... } }
上面代碼中,#x
是一個私有屬性,它的讀寫都經過get #x()
和set #x()
來完成。
1.8 this 的指向
類的方法內部若是含有this
,它默認指向類的實例。可是,必須很是當心,一旦單獨使用該方法,極可能報錯。
1 class Logger { 2 printName(name = 'there') { 3 this.print(`Hello ${name}`); 4 } 5 6 print(text) { 7 console.log(text); 8 } 9 } 10 11 const logger = new Logger(); 12 const { printName } = logger; 13 printName(); // TypeError: Cannot read property 'print' of undefined
上面代碼中,printName
方法中的this
,默認指向Logger
類的實例。可是,若是將這個方法提取出來單獨使用,this
會指向該方法運行時所在的環境,由於找不到print
方法而致使報錯。
一個比較簡單的解決方法是,在構造方法中綁定this
,這樣就不會找不到print
方法了。
1 class Logger { 2 constructor() { 3 this.printName = this.printName.bind(this); 4 } 5 // ... 6 }
另外一種解決方法是使用箭頭函數
class Logger { constructor() { this.printName = (name = 'there') => { this.print(`Hello ${name}`); }; } // ... }
還有一種解決方法是使用Proxy
,獲取方法的時候,自動綁定this //
[TODO] -- proxy ?
1 function selfish (target) { 2 const cache = new WeakMap(); 3 const handler = { 4 get (target, key) { 5 const value = Reflect.get(target, key); 6 if (typeof value !== 'function') { 7 return value; 8 } 9 if (!cache.has(value)) { 10 cache.set(value, value.bind(target)); 11 } 12 return cache.get(value); 13 } 14 }; 15 const proxy = new Proxy(target, handler); 16 return proxy; 17 } 18 19 const logger = selfish(new Logger());
1.9 name 屬性
因爲本質上,ES6 的類只是 ES5 的構造函數的一層包裝,因此函數的許多特性都被Class
繼承,包括name
屬性。
1 class Point {} 2 Point.name // "Point"
name
屬性老是返回緊跟在class
關鍵字後面的類名。
1. 10 class的取值函數 getter 和存值函數 setter
與 ES5 同樣,在「類」的內部可使用get
和set
關鍵字,對某個屬性設置存值函數和取值函數,攔截該屬性的存取行爲。
class MyClass { constructor() { // ... } get prop() { return 'getter'; } set prop(value) { console.log('setter: '+value); } } let inst = new MyClass(); inst.prop = 123; // setter: 123 inst.prop // 'getter'
上面代碼中,prop
屬性有對應的存值函數和取值函數,所以賦值和讀取行爲都被自定義了。
存值函數和取值函數是設置在屬性的 Descriptor 對象上的。
1 class CustomHTMLElement { 2 constructor(element) { 3 this.element = element; 4 } 5 6 get html() { 7 return this.element.innerHTML; 8 } 9 10 set html(value) { 11 this.element.innerHTML = value; 12 } 13 } 14 15 var descriptor = Object.getOwnPropertyDescriptor( 16 CustomHTMLElement.prototype, "html" 17 ); 18 19 "get" in descriptor // true 20 "set" in descriptor // true
上面代碼中,存值函數和取值函數是定義在html
屬性的描述對象上面,這與 ES5 徹底一致。
1.11 class 的 generator方法
若是某個方法以前加上星號(*
),就表示該方法是一個 Generator 函數。
class Foo { constructor(...args) { this.args = args; } * [Symbol.iterator]() { for (let arg of this.args) { yield arg; } } } for (let x of new Foo('hello', 'world')) { console.log(x); } // hello // world
上面代碼中,Foo
類的Symbol.iterator
方法前有一個星號,表示該方法是一個 Generator 函數。Symbol.iterator
方法返回一個Foo
類的默認遍歷器,for...of
循環會自動調用這個遍歷器。
1. 12 class的靜態方法
類至關於實例的原型,全部在類中定義的方法,都會被實例繼承。若是在一個方法前,加上static
關鍵字,就表示該方法不會被實例繼承,而是直接經過類來調用,這就稱爲「靜態方法」。
1 class Foo { 2 static classMethod() { 3 return 'hello'; 4 } 5 } 6 7 Foo.classMethod() // 'hello' 8 9 var foo = new Foo(); 10 foo.classMethod() 11 // TypeError: foo.classMethod is not a function
上面代碼中,Foo
類的classMethod
方法前有static
關鍵字,代表該方法是一個靜態方法,能夠直接在Foo
類上調用(Foo.classMethod()
),而不是在Foo
類的實例上調用。若是在實例上調用靜態方法,會拋出一個錯誤,表示不存在該方法。
注意,若是靜態方法包含this
關鍵字,這個this
指的是類,而不是實例。
1 class Foo { 2 static bar () { 3 this.baz(); 4 } 5 static baz () { 6 console.log('hello'); 7 } 8 baz () { 9 console.log('world'); 10 } 11 } 12 13 Foo.bar() // hello
上面代碼中,靜態方法bar
調用了this.baz
,這裏的this
指的是Foo
類,而不是Foo
的實例,等同於調用Foo.baz
。另外,從這個例子還能夠看出,靜態方法能夠與非靜態方法重名。
父類的靜態方法,能夠被子類繼承。
class Foo { static classMethod() { return 'hello'; } } class Bar extends Foo { } Bar.classMethod() // 'hello'
上面代碼中,父類Foo
有一個靜態方法,子類Bar
能夠調用這個方法。
靜態方法也是能夠從super
對象上調用的。
1 class Foo { 2 static classMethod() { 3 return 'hello'; 4 } 5 } 6 7 class Bar extends Foo { 8 static classMethod() { 9 return super.classMethod() + ', too'; 10 } 11 } 12 13 Bar.classMethod() // "hello, too"
1. 13 class的靜態屬性 和 示例屬性
靜態屬性指的是 Class 自己的屬性,即Class.propName
,而不是定義在實例對象(this
)上的屬性。
class Foo { } Foo.prop = 1; Foo.prop // 1
上面的寫法爲Foo
類定義了一個靜態屬性prop
。
目前,只有這種寫法可行,由於 ES6 明確規定,Class 內部只有靜態方法,沒有靜態屬性。
// 如下兩種寫法都無效 class Foo { // 寫法一 prop: 2 // 寫法二 static prop: 2 } Foo.prop // undefined
目前有一個靜態屬性的提案,對實例屬性和靜態屬性都規定了新的寫法。
(1)類的實例屬性
類的實例屬性能夠用等式,寫入類的定義之中。
1 class MyClass { 2 myProp = 42; 3 4 constructor() { 5 console.log(this.myProp); // 42 6 } 7 }
上面代碼中,myProp
就是MyClass
的實例屬性。在MyClass
的實例上,能夠讀取這個屬性。
之前,咱們定義實例屬性,只能寫在類的constructor
方法裏面。
class ReactCounter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } }
上面代碼中,構造方法constructor
裏面,定義了this.state
屬性。
有了新的寫法之後,能夠不在constructor
方法裏面定義。
class ReactCounter extends React.Component { state = { count: 0 }; }
這種寫法比之前更清晰。
爲了可讀性的目的,對於那些在constructor
裏面已經定義的實例屬性,新寫法容許直接列出。
class ReactCounter extends React.Component { state; constructor(props) { super(props); this.state = { count: 0 }; } }
(2)類的靜態屬性
類的靜態屬性只要在上面的實例屬性寫法前面,加上static
關鍵字就能夠了。
class MyClass { static myStaticProp = 42; constructor() { console.log(MyClass.myStaticProp); // 42 } }
一樣的,這個新寫法大大方便了靜態屬性的表達。
// 老寫法 class Foo { // ... } Foo.prop = 1; // 新寫法 class Foo { static prop = 1; }
上面代碼中,老寫法的靜態屬性定義在類的外部。整個類生成之後,再生成靜態屬性。這樣讓人很容易忽略這個靜態屬性,也不符合相關代碼應該放在一塊兒的代碼組織原則。另外,新寫法是顯式聲明(declarative),而不是賦值處理,語義更好。
1. 14 new target
new
是從構造函數生成實例對象的命令。ES6 爲new
命令引入了一個new.target
屬性,該屬性通常用在構造函數之中,返回new
命令做用於的那個構造函數。若是構造函數不是經過new
命令調用的,new.target
會返回undefined
,所以這個屬性能夠用來肯定構造函數是怎麼調用的。
1 function Person(name) { 2 if (new.target !== undefined) { 3 this.name = name; 4 } else { 5 throw new Error('必須使用 new 命令生成實例'); 6 } 7 } 8 9 // 另外一種寫法 10 function Person(name) { 11 if (new.target === Person) { 12 this.name = name; 13 } else { 14 throw new Error('必須使用 new 命令生成實例'); 15 } 16 } 17 18 var person = new Person('張三'); // 正確 19 var notAPerson = Person.call(person, '張三'); // 報錯
上面代碼確保構造函數只能經過new
命令調用。
Class 內部調用new.target
,返回當前 Class。
class Rectangle { constructor(length, width) { console.log(new.target === Rectangle); this.length = length; this.width = width; } } var obj = new Rectangle(3, 4); // 輸出 true
須要注意的是,子類繼承父類時,new.target
會返回子類。
class Rectangle { constructor(length, width) { console.log(new.target === Rectangle); // ... } } class Square extends Rectangle { constructor(length) { super(length, length); } } var obj = new Square(3); // 輸出 false
上面代碼中,new.target
會返回子類。
利用這個特色,能夠寫出不能獨立使用、必須繼承後才能使用的類。
class Shape { constructor() { if (new.target === Shape) { throw new Error('本類不能實例化'); } } } class Rectangle extends Shape { constructor(length, width) { super(); // ... } } var x = new Shape(); // 報錯 var y = new Rectangle(3, 4); // 正確
上面代碼中,Shape
類不能被實例化,只能用於繼承。
注意,在函數外部,使用new.target
會報錯。
您在使用ES6 class類開發過程當中有遇到什麼問題?
歡迎留言交流...