關(guān)于構(gòu)造函數(shù)中this和prototype定義的屬性和方法的不同

this定義的屬性和方法,是生成的每個(gè)實(shí)例有屬于自己的屬性和方法;

prototype定義的屬性和方法,是每個(gè)實(shí)例共同擁有一份構(gòu)造函的引用屬性和方法;

  • this定義
function Admin(food) {
   this.food = food || "米飯";
   this.arrList = [];
   this.eat = function () {
       console.log("吃點(diǎn)"+this.food)
   }
 }

 let son1 = new Admin("香蕉");
 let son2 = new Admin("蘋(píng)果");

 console.log(son1.food);  
 son1.eat(); // 吃點(diǎn)香蕉
 son1.arrList.push(1);
 console.log(son1.arrList); // [1]

 console.log(son2.food);
 son2.eat();  // 吃點(diǎn)蘋(píng)果
 son2.arrList.push(2);
 console.log(son2.arrList); // [2]
  

*prototype

function Admin() {
}

Admin.prototype.food= "";
Admin.prototype.arrList= [];
Admin.prototype.eat = function () {
    console.log("吃點(diǎn)"+this.food)
}

let son1 = new Admin();
let son2 = new Admin();

son1.food = "香蕉";
son1.eat(); // 吃點(diǎn)香蕉
son1.arrList.push(1);
console.log(son1.arrList); // [1]

son2.eat(); // 吃點(diǎn)
son2.food = "蘋(píng)果";
son2.eat(); // 吃點(diǎn)蘋(píng)果
son2.arrList.push(2);
console.log(son2.arrList); // [1,2]

由上可以看出this是實(shí)例自己獨(dú)有的,而prototype中屬性為引用數(shù)據(jù)類型是所有實(shí)例共有的;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容