千鋒web前端開發(fā)項(xiàng)目教程_1000集完全零基礎(chǔ)入門HTML5+CSS3+JS到

ES5 方法創(chuàng)建類
js運(yùn)用了面向?qū)ο蟮乃枷?,但是卻沒有類的語法
解決方案:用函數(shù)模擬類,被當(dāng)作類的函數(shù)本質(zhì)是構(gòu)造函數(shù)
??function Student(name,age,score){
??this.name = name;
????this.age = age;
????this.score = score;
????this.doHomework = function(){
console.log("doHomework");
????}
????this.eat = function (){
??????console.log("eat");
}
????當(dāng)一個(gè)成員函數(shù)要使用其他的成員,必須添加前綴this
????this.showValue = function(){
??????console.log(this.name,this.age,this.score)
??????this.eat()
??????this.doHomework()
????}
??}
let s1 = new Student("aa",30,100);
普通函數(shù)與構(gòu)造函數(shù)的區(qū)別:
?? 1.習(xí)慣上構(gòu)造函數(shù)首字母大寫
?????2.構(gòu)造函數(shù)必須和new連用
?????3.構(gòu)造函數(shù)不能添加return,因?yàn)樽詣?dòng)返回的是地址
ES6 創(chuàng)建類
class 類名{
??//構(gòu)造函數(shù) -> new時(shí)調(diào)用的函數(shù)
??constructor(參數(shù)列表){
?????
??}
??去掉function的普通函數(shù)
}