this定义的属性和方法,是生成的每个实例有属于自己的属性和方法;
prototype定义的属性和方法,是每个实例共同拥有一份构造函的引用属性和方法;
- this定义
function Admin(food) {
this.food = food || "米饭";
this.arrList = [];
this.eat = function () {
console.log("吃点"+this.food)
}
}
let son1 = new Admin("香蕉");
let son2 = new Admin("苹果");
console.log(son1.food);
son1.eat(); // 吃点香蕉
son1.arrList.push(1);
console.log(son1.arrList); // [1]
console.log(son2.food);
son2.eat(); // 吃点苹果
son2.arrList.push(2);
console.log(son2.arrList); // [2]
*prototype
function Admin() {
}
Admin.prototype.food= "";
Admin.prototype.arrList= [];
Admin.prototype.eat = function () {
console.log("吃点"+this.food)
}
let son1 = new Admin();
let son2 = new Admin();
son1.food = "香蕉";
son1.eat(); // 吃点香蕉
son1.arrList.push(1);
console.log(son1.arrList); // [1]
son2.eat(); // 吃点
son2.food = "苹果";
son2.eat(); // 吃点苹果
son2.arrList.push(2);
console.log(son2.arrList); // [1,2]
由上可以看出this是实例自己独有的,而prototype中属性为引用数据类型是所有实例共有的;