家人们先来看看一个 构造函数
function Car(name) {
this.name = name;
this.move = function () {
console.log('我是' + this.name + "准备好了吗!发车了哦");
return this.src
}
this.init = function () {
console.log('初始化')
}
}
var car1 = new Car('宝马')
var car2 = new Car('奔驰')
console.log(car1.move === car2.move); // false
这儿为什么是 false
呢?
因为实例化两个对象,两个对象都有一个move方法,但是每个对象的move方法都存在不同的内存地址中,所以 不相等
同理,每一个构造函数新创建出来的实例对象中的方法都不一样,那如果创造很多对象就会有很多方法,就会造成内存浪费!
这个就叫 方法过载
解决方法:添加到原型上
//构造函数
function Student(name, age) {
this.name = name;
this.age = age;
// //方法过载
// this.show = function () {
// console.log("造化钟神秀");
// }
}
//解决方法 添加到原型上
Student.prototype.show = function () {
console.log("造化钟神秀");
}
// 根据构造函数 创建实例对象
var p1 = new Student("张三", 11);
var p2 = new Student("李四", 22);
console.log(p1);
console.log(p2);
console.log('==================');
console.log(p1.show === p2.show) // true
因为 实例对象 共享(继承)原型方法 举个例子(你可以姓张,你同宗族的人也可以姓张 因为你们都是一脉相承 )
console.log(p1.__proto__ === Student.prototype) // true 实例对象的隐式原型 等于 构造函数的显示原型
console.log(p2.__proto__ === Student.prototype) // true
console.log(Student.prototype.constructor === Student) // true 构造原型的constructor指向构造函数本身