原型分为显示原型(prototype)隐式原型(__proto__)。
其对应的原型关系如下:
1.每个class都有显示原型prototype。
2.每个对象实例都有一个隐式原型__proto__指向对应的class的prototype。
3.对象实例的__proto__指向对应的class的prototype。
基于原型的执行规定
获取属性xialuo.name或者执行办法xialuo。sayHi()时:
1.先在本身属性和办法寻找。
2.如果找不到则主动去__proto__中查找,若始终往上查找到Object这个顶级对象仍未找到,则返回Object.prototype.__proto__下的值为null。
什么是原型链?
答:每个实例对象(object)都有一个公有属性(__proto__ )指向它的构造函数的原型对象(prototype)。该原型对象也有一个本人的原型对象(__proto__),层层向上直到一个对象的原型对象为 null。由此造成的链式构造称为原型链。
其图示如下所示:
其对应代码如下所示:
class Person{ constructor(name, number){ this.name = name; this.number = number; } eat(){}};class Student extends Person{ constructor(name, number){ super(name, number) } sayHi(){}}let xialuo = new Student();//其关系如下:xialuo.__proto__ = Student.prototype;console.log( xiaoluo.hasOwnProperty("name") )//trueconsole.log( xiaoluo.hasOwnProperty("eat") )//falsexialuo.instanceof Student //truexialuo.instanceof Person //truexialuo.instanceof Object //true