更新時間:2021-12-15 來源:黑馬程序員 瀏覽量:
//定義類
class Person {
constructor(name) { //構(gòu)造方法
this.name = name; //為新創(chuàng)建的對象添加name屬性
}
}
//利用類創(chuàng)建對象
var pl = new Person('張三'); //創(chuàng)建p1對象
var p2 = new Person('李四'); //創(chuàng)建p2對象
console.log(pl.name); //訪問pl對象的name屬性
console.log(p2.name); //訪問 p2對象的 name屬性
在上述代碼中,constructor()構(gòu)造方法在使用類創(chuàng)建對象時會自動調(diào)用,在調(diào)用時會將實(shí)例化的參數(shù)傳過來。在命名習(xí)慣上,類名使用首字母大寫的形式。如果一個類中沒有編寫Constructor()構(gòu)造方法,程序會在類中自動創(chuàng)建一個constructor()構(gòu)造方法。
主類中可以編寫所有對象共有的方法,示例代碼如下。
class Person { //構(gòu)造方法
constructor(name) {
this.name = name;
}
say() { //在類中定義一個say()方法
console.log('你好,我叫' + this.name);
}
}
var pl = new Person('張三');
Pl.say(); //輸出結(jié)果:你好,我叫張三
在上述代碼中,say()方法就是在類中定義的方法。在定義方法時,不需要使用function關(guān)鍵字,并且多個方法之間不需要使用逗號分隔。在say()方法中,this表示實(shí)例對象,如果是調(diào)用了pl對象的say()方法,則this就表示pl, this.name表示pl.name。