剖析p.age属性值的获取过程,为何最终得到undefined?
class Person {
constructor() {
this.name = 'zhangshan';
}
say(str) {
console.log(str);
}
}
let p = new Person();
console.log(p.age); //undefined
第一步:在p对象自身找,但是没有找到age属性
// p对象
{
name: 'zhangshan'
__proto__: Person.prototype
}
第二步:顺着原型链在p.__proto__(也就是Person.prototype)上找,还是没有找到age属性
// p.__proto__ === Person.prototype //true
{
constructor: class Person
say: ƒ say(str)
__proto__: Object
}
第三步:顺着原型链在p.__proto__.__proto__(也就是Object.prototype)上找,还是没有找到age属性
// p.__proto__.__proto__ === Object.prototype //true
{
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()
}
第四步:顺着原型链在p.__proto__.__proto__.__proto__(也就是Object.prototype.__proto__)上找,发现Object.prototype.__proto__为null,于是宣布寻找失败,返回undefined
// p.__proto__.__proto__.__proto__ === Object.prototype.__proto__ //true
null
如何证明实例对象p与 Object.prototype的原型继承关系?
在Object.prototype对象上新增一个属性,在实例化对象上能成功访问到该属性,便能证明继承关系
Object.prototype.age = 10;
console.log(p.age); // 10
原型链取值图
Object.prototype.__proto__为什么会是null?
可以看到下面这些构造函数的原型对象都是由Object构造函数实例化出来的
理论上来讲Object.prototype.__proto__也应该是一个对象,也应该是由Object实例化出来的,但是这样会导致原型链变成一个死循环,出于这个考虑Object.prototype.__proto__被定义为null
Function.__proto__ === String.__proto__ // true
String.__proto__ === Number.__proto__ // true
Number.__proto__ === Object.__proto__ // true
Object.__proto__ === Function.__proto__ // true
Function.prototype.__proto__ === String.prototype.__proto__ // true
String.prototype.__proto__ === Number.prototype.__proto__ // true
Number.prototype.__proto__ === Object.prototype.__proto__ // false
Object.__proto__ === Function.prototype.__proto__ // false
本文详细剖析了JavaScript中实例对象p的age属性值为何获取到的是undefined,通过追踪原型链的过程,解释了属性查找机制,并揭示了Object.prototype.__proto__为null的原因。
323

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



