如图所示:
1.instanceof检测构造函数与实例的关系:
function Person () {.........}
person = new Person ()
res = person instanceof Person
res // true
2.实例继承原型上的定义的属性:
function Person () {........}
Person.prototype.type = 'object n'
person = new Person ()
res = person.type
res // object n
3.实例访问 ===> 原型
实例通过__proto__访问到原型 person.proto=== Person.prototype
4.原型访问 ===> 构造函数
原型通过constructor属性访问构造函数 Person.prototype.constructor === Person
5.实例访问===>构造函数
person.proto.constructor === Person
在读取一个实例的属性的过程中,如果属性在该实例中没有找到,那么就会循着 proto 指定的原型上去寻找,如果还找不到,则寻找原型的原型:
1.实例上寻找
function Person() {}
Person.prototype.type = "object name Person"; person = new Person(); person.type = "我是实例的自有属性"; res = Reflect.ownKeys(person); //尝试获取到自有属性 console.log(res); res = person.type; console.log(res); //我是实例的自有属性(通过原型链向上搜索优先搜索实例里的)
2.原型上寻找
function Person() {}
Person.prototype.type = "object name Person"; person = new Person(); res = Reflect.ownKeys(person); //尝试获取到自有属性 console.log(res); res = person.type; console.log(res); //object name Person
3.原型的原型上寻找
function Person() {}
Person.prototype.type = "object name Person"; function Child() {} Child.prototype = new Person(); p = new Child(); res = [p instanceof Object, p instanceof Person, p instanceof Child]; console.log(res); //[true, true, true] p同时属于Object,Person, Child res = p.type; //层层搜索 console.log(res); //object name Person (原型链上搜索) console.dir(Person); console.dir(Child);
4.原型链上搜索
function Person() {}
Person.prototype.type = "object name Person"; function Child() {} Child.prototype = new Person(); p = new Child(); res = p.__proto__; console.log(res); //Person {} res = p.__proto__.__proto__; console.log(res); //Person {type:'object name Person'} res = p.__proto__.__proto__.__proto__; console.log(res); //{.....} res = p.__proto__.__proto__.__proto__.__proto__; console.log(res); //null