class的概念
一、我們為什么要用到class類?
因為通過class類來創建對象,使得開發者不必寫重復的代碼,以達到代碼復用的目的。它基於的邏輯是,兩個或多個對象的結構功能類似,可以抽象出一個模板,
依照模板復制出多個相似的對象。就像汽車制造商一遍一遍地復用相同的模板來制造大量的汽車車,我們暫且把class理解為一個模板。
但是為什么我們不用function函數用來重復使用呢?
因為funcion聲明是需要狀態提升的,而class不是,class需要先聲明再使用。
二、class類的語法
1 class Student{ 2 constructor(name,age,sex){ 3 this.name = name 4 this.age= age 5 this.sex = sex 6 } 7 8 read(){console.log(this.name+this.age+this.sex)} 9 } 10 var Tom =new Student('tom',21,'男') 11 Tom.read()
Tom是通過類Student實例化出來的對象。對象Tom是按照Student這個模板,實例化出來的對象。實例化出來的對象擁有預先定制好的結構和功能。
2.1 constructor 構造方法
constructor方法是一個特殊的方法,用來創建並初始化一個對象。在一個class中只能有一個命名為constructor的特殊方法,如果包含多個將會報錯。
constructor中可以通過super關鍵字,調用父類的constructor方法。
2.2 static (靜態方法)
通過static關鍵字為一個class創建靜態方法
1 class student{ 2 //靜態屬性 3 static p = 2; 4 //構造方法 5 constructor(name,age,sex){ 6 this.name=name 7 this.age=age 8 this.sex=sex 9 } 10 //實例方法 dream(){console.log('月薪過萬。')} 12 } 13 // 靜態屬性調用 14 console.log(student.p)
2.3 類的繼承 extends
1 class A { 2 constructor(){ 3 this.name = 'Marry' 4 this.age= 18 5 } 6 read(){console.log(this.name+this.age)} 7 } 8 class B extends A { 9 constructor(props) { 10 super(props) 11 } 12 s(){ 13 console.log(this.name+this.age) 14 } 15 } 16 var b = new B(); 17 b.s()
當實例 b 調用 s 方法時,b 本身沒有 name和age,會根據繼承找到A
2.4“this”指向問題
class中的this指向實例時的對象。
2.5 super( )關鍵字
關鍵字super用於調用父類相應的方法,這是相較於原型繼承的一個好處
三.總體的寫法
1 // 創建一個類存放特有的屬性和方法,用來實例對象。 2 class Student{ 3 // 靜態屬性只屬於Student的屬性 4 static s = "180"; 5 // 靜態方法只屬於Student的方法 6 static m(){ 7 console.log("靜態方法") 8 } 9 // 構造方法 10 constructor(props){ 11 //實例屬性 12 this.name=props.name; 13 this.age=props.age; 14 this.sex=props.sex; 15 } 16 // 實例方法 17 students(){ 18 console.log(this.name+this.age+this.sex) 19 20 } 21 } 22 // 靜態屬性調用 23 console.log(Student.s) 24 // 實例化對象 25 var S1 = new Student('tom',21,'男'); 26 // 調用方法 27 S1.students()
以上純屬個人理解,如有疑問歡迎留言