1、什么叫做靜態方法?
1.1、類相當於實例的原型, 所有在類中定義的方法, 都會被實例繼承。如果在一個方法前,加上Static關鍵字,就表示該方法不會被繼承,而是直接通過類來調用,這被稱為 “靜態方法”。
1.2、我們可以從代碼上進行更深的理解。
下面的代碼中,Sea類的classMethod方法前有static關鍵字,表明該方法是一個靜態方法,可以直接在Sea類上調用(Sea.classMethod()),而不是在Sea類的實例上調用靜態方法,會拋出一個錯誤,表示不存在該方法。
父類的靜態方法可以被子類繼承。
1 class Sea { 2 static classMethod(){ 3 return 'hello' 4 } 5 } 6 Sea.classMethod() //'hello' 7 var foo =new Foo(); 8 foo.classMethod() 9 // TypeError: foo.classMethod is not a function
下面代碼中。父類Sea有一個靜態方法,子類Ocean可以調用這個方法。
靜態方法也是可以從super對象上調用。
1 class Sea{ 2 static classMethod(){ 3 return 'hello' 4 } 5 } 6 class Ocean extends Sea{} 7 Ocean.clsaaMethod(); //'hello'
1.3、下面就是整個靜態方法的使用(完整的可以直接用)
1 class Sea{ 2 static classMethod(){ 3 return 'hello' 4 } 5 } 6 class Ocean extends Sea{ 7 static classMethod(){ 8 return super.clsassMethod()+',too' 9 } 10 } 11 Ocean.classMethod();
2、什么叫靜態屬性?
2.1、靜態屬性指的是Class本身的屬性,即Class.propname,而不是定義在實例對象(this)上的屬性。
2.2、我們可以從代碼上進行更深的理解。
下面的寫法為Sea定義了一個靜態prop,目前,只有這種寫法可行,因為ES6明確規定,Class內部只有靜態方法,沒有靜態屬性。
1 class Foo {} 2 Foo.prop = 1; 3 Foo.prop // 1
2.3、ES7 有一個靜態屬性的提案, 目前 Babel 轉碼器支持。這個提案對實例屬性和靜態屬性, 都規定了新的寫法。
2.3.1、 類的實例屬性
類的實例屬性可以用等式, 寫入類的定義之中。
1 // 以下兩種寫法都無效 2 class Sea { 3 // 寫法一 4 prop: 2 5 // 寫法二 6 static prop: 2 7 } 8 Sea.prop // undefined
2.4、下面代碼中,myProp就是MyClass的實例屬性。在MyClass的實例上,可以讀取這個屬性。以前,我們定義實例屬性,只能寫在類的從structor方法里面。
1 calss MyClass{ 2 myProp=42; 3 constructor(){ 4 console.log(this.myProp); 5 } 6 }
2.5、下面代碼中,構造方法constructor里面,定義了this.state屬性。有了新的寫法以后,可以不在constructor方法里面定義。
1 class ReactCounter extends React.Component { 2 constructor(props) { 3 super(props); 4 this.state = { 5 count: 0 6 }; 7 } 8 }
這種寫法比以前更清晰。
為了可讀性的目的, 對於那些在constructor里面已經定義的實例屬性, 新寫法允許直接列出。
1 class ReactCounter extends React.Component { 2 state = { 3 count: 0 4 }; 5 }
2.6、下面即使整個靜態屬性的使用(完整的可以直接用)
1 class ReactCounter extends React.Component { 2 constructor(props) { 3 super(props); 4 this.state = { 5 count: 0 6 }; 7 } 8 state; 9 }
3、類的靜態屬性
3.1、類的靜態屬性只要在上面的實例屬性寫在前面, 加上static關鍵字就可以了。
1 class MyClass { 2 static myStaticProp = 42; 3 constructor() { 4 console.log(MyClass.myProp); // 42 5 } 6 }
同樣的,這個寫法大大方便了靜態屬性的表達。
1 // 老寫法 2 class Foo {} 3 Foo.prop = 1; 4 // 新寫法 5 class Foo { 6 static prop = 1; 7 }
上面代碼中, 老寫法的靜態屬性定義在類的外部。 整個類生成以后, 再生成靜態屬性。 這樣讓人很容易忽略這個靜態屬性, 也不符合相關代碼應該放在一起的代碼組織原則。 另外, 新寫法是顯式聲明( declarative), 而不是賦值處理, 語義更好。