JS 原型链
javascript原型链剖析
2019年05月15日 21:57:48 lihefei_coder 阅读数:19
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lihefei_coder/article/details/90246124
剖析p.age属性值的获取过程,为何最终得到undefined?
class Person {
constructor() {
this.name = 'zhangshan';
}
say(str) {
console.log(str);
}
}
let p = new Person();
console.log(p.age); //undefined
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
// p对象
{
name: 'zhangshan'
__proto__: Person.prototype
}
- 1
- 2
- 3
- 4
- 5
第二步:顺着原型链在p.__proto__(也就是Person.prototype)上找,还是没有找到age属性
// p.__proto__ === Person.prototype //true
{
constructor: class Person
say: ƒ say(str)
__proto__: Object
}
- 1
- 2
- 3
- 4
- 5
- 6
第三步:顺着原型链在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__()
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
第四步:顺着原型链在p.__proto__.__proto__.__proto__(也就是Object.prototype.__proto__)上找,发现Object.prototype.__proto__为null,于是宣布寻找失败,返回undefined
// p.__proto__.__proto__.__proto__ === Object.prototype.__proto__ //true
null
- 1
- 2