一图胜千言:构造函数 原型对象 实例对象三者关系; 原型链指的对象与原型构成的链式数据结构

function Person(){}
function teacher(){}
teacher.prototype = Object.create(Person);
teacher.prototype.constructor = teacher;
Object.create 的作用是 :返回指定原型的新对象,这里指定原型是Person构造函数:对应图:

验证一下:
const t = new teacher();
console.log(teacher.prototype.__proto__ === Person);
console.log(t.__proto__.__proto__ === Person);

如果是这样呢?
function Person() {}
function teacher() {}
const p = new Person();
teacher.prototype = p;//==>teacher.prototype.__proto__==> Person.prototype
teacher.prototype.constructor = teacher; // 不加这句,teacher.prototype.constructor 是Perosn
对应图:

验证一下:
const t = new teacher();
console.log(teacher.prototype.__proto__ === Person.prototype);
console.log(t.__proto__.__proto__ === Person.prototype);

没有问题,理解完全文,应该可以对原型和原型链有一个清晰的理解。
本文通过实例解析了JavaScript中构造函数、原型对象和实例对象之间的关系,以及原型链的工作原理。通过Object.create()创建原型链,并展示了两种不同的原型设置方式,验证了原型对象的继承关系。通过这种方式,读者可以更清晰地理解JavaScript的原型和原型链概念。
626

被折叠的 条评论
为什么被折叠?



