原型模式:
将所有对象共享的方法或属性,绑定在对应的构造函数的原型中
function Student(name, age) { //构造函数Student 类
this.name = name;
this.age = age;
// this.eat = function () {
// console.log(this.name + "正在吃");
// }
}
构造函数的 prototype 原型
将构造函数中的eat函数写到prototype原型上
Student.prototype.eat = function () { //prototype 原型
console.log(this.name + "正在吃");
}
var stu1 = new Student("王一",21);
stu1.eat(); //王一正在吃
var stu2 = new Student("张三",23);
stu2.eat(); //张三正在吃
console.log(stu1.eat==stu2.eat); //true
//什么内容写在原型上:共有的共享的内容写到原型上
在实例化对象中的__proto__ 等于 构造函数中的 prototype ,等于对应的原型链
function Student(name, age) {
this.name = name;
this.age = age;
}
// 构造函数的 prototype 原型
Student.prototype.eat = function () {
console.log(this.name + "正在吃");
}
var stu1 = new Student("王一", 21);
var stu2 = new Student("张三", 23);
// 每一个实例化的对象 都包含了一个 __proto__ == 构造函数的prototype
stu1.__proto__.showInfo = function () { // 相当于Student.prototype.showInfo=function(){}
console.log("名称为:" + this.name + ",年龄为:" + this.age);
};
stu1.showInfo();
stu2.showInfo();
console.log(stu2.__proto__.constructor);
__proto__原型中的 constructor 对应的是 构造函数(类)
每个对象实例都具有 constructor 属性,它指向创建该实例的构造器函数。
通过函数创建的对象,如果有公用的方法或属性,可以直接写到对应的原型中,节约内存。
构造函数中 prototype
实际对象中__proto__
原型的执行顺序:先执行构造函数,如果构造函数中没有,再找原型中是否包含。