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í)例共有的;