修改原型
修改构造函数的原型,不会影响实例对象隐式原型和构造函数显示原型是否相等。
//1、创建一个构造函数
function Teacher(name) {
this.name = name;
}
//2、修改原型,在原型上添加一个方法getName
Teacher.prototype.getName = function () {
console.log(this.name);
}
//3、创建一个实例对象
const t = new Teacher("语文张三");
//4、修改原型后,比较
console.log(t.__proto__ === Teacher.prototype);//true
console.log(t.__proto__ === t.constructor.prototype);//true
重写原型
重写原型,实例对象通过xxx.constructor的方式指向的是Object这个根构造函数
//1、创建一个构造函数
function Student(name) {
this.name = name;
}
//2、重写原型
Student.prototype = {
getName: function () {
console.log(this.name);
}
}
//3、创建一个实例对象;
//重写原型,直接给Student的原型对象用对象进行赋值时,p的构造韩式指向根构造函数Object
const s = new Student("学生李四");//内部:s(this).__proto__ = Student.prototype
//4、重写原型后,比较构造函数的显示原型和实例对象的隐式原型是否相等
console.log(s.__proto__ === Student.prototype);//true
// 6、重写原型后,p.constructor指向的是根构造函数Object
console.log(s.__proto__ === s.constructor.prototype);//false