class的概念
一、我們?yōu)槭裁匆玫絚lass類?
因為通過class類來創(chuàng)建對象九孩,使得開發(fā)者不必寫重復的代碼先馆,以達到代碼復用的目的。它基于的邏輯是躺彬,兩個或多個對象的結構功能類似煤墙,可以抽象出一個模板,依照模板復制出多個相似的對象。就像汽車制造商一遍一遍地復用相同的模板來制造大量的汽車車宪拥,我們暫且把class理解為一個模板.
但是為什么我們不用function函數(shù)用來重復使用呢仿野?因為funcion聲明是需要狀態(tài)提升的,而class不是江解,class需要先聲明再使用设预。
二、class類的語法
class Student{
constructor(name,age,sex){
this.name = name
this.age= age
this.sex = sex
}
read(){console.log(this.name+this.age+this.sex)}
}
var Tom =new Student('tom',21,'男')
Tom.read()
Tom是通過類Student實例化出來的對象犁河。對象Tom是按照Student這個模板鳖枕,實例化出來的對象魄梯。實例化出來的對象擁有預先定制好的結構和功能。
2.1 constructor 構造方法
constructor方法是一個特殊的方法宾符,用來創(chuàng)建并初始化一個對象酿秸。在一個class中只能有一個命名為constructor的特殊方法,如果包含多個將會報錯魏烫。
constructor中可以通過super關鍵字辣苏,調(diào)用父類的constructor方法。
2.2 static (靜態(tài)方法)
通過static關鍵字為一個class創(chuàng)建靜態(tài)方法
class student{
//靜態(tài)屬性
static p = 2;
//構造方法
constructor(name,age,sex){
this.name=name
this.age=age
this.sex=sex
}
//實例方法 dream(){console.log('月薪過萬哄褒。')}
}
// 靜態(tài)屬性調(diào)用
console.log(student.p)
2.3 類的繼承 extends
class A {
constructor(){
this.name = 'Marry'
this.age= 18
}
read(){console.log(this.name+this.age)}
}
class B extends A {
constructor(props) {
super(props)
}
s(){
console.log(this.name+this.age)
}
}
var b = new B();
b.s()
當實例 b 調(diào)用 s 方法時稀蟋,b 本身沒有 name和age,會根據(jù)繼承找到A
2.4“this”指向問題
class中的this指向?qū)嵗龝r的對象呐赡。
2.5 super( )關鍵字
關鍵字super用于調(diào)用父類相應的方法退客,這是相較于原型繼承的一個好處
三.總體的寫法
// 創(chuàng)建一個類存放特有的屬性和方法,用來實例對象链嘀。
class Student{
// 靜態(tài)屬性只屬于Student的屬性
static s = "180";
// 靜態(tài)方法只屬于Student的方法
static m(){
console.log("靜態(tài)方法")
}
// 構造方法
constructor(props){
//實例屬性
this.name=props.name;
this.age=props.age;
this.sex=props.sex;
}
// 實例方法
students(){
console.log(this.name+this.age+this.sex)
}
}
// 靜態(tài)屬性調(diào)用
console.log(Student.s)
// 實例化對象
var S1 = new Student('tom',21,'男');
// 調(diào)用方法
S1.students()