面试题答案
一键面试在JavaScript中,当访问一个对象的属性时,原型链的属性查找机制如下:
- 首先在对象自身的属性中查找,如果找到,则返回该属性的值,查找结束。
- 如果在对象自身属性中未找到,则会沿着原型链向上查找,即查找对象的
[[Prototype]]
指向的原型对象。 - 如果在原型对象中找到该属性,则返回该属性的值,查找结束。
- 如果在原型对象中未找到,继续沿着原型链向上查找,重复步骤2和3,直到原型链的顶端(
Object.prototype
)。如果在Object.prototype
中也未找到,则返回undefined
。
例如:
function Parent() {
this.parentProp = 'parent value';
}
Parent.prototype.parentProtoProp = 'parent prototype value';
function Child() {
this.childProp = 'child value';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
let childInstance = new Child();
// 访问不存在的属性
console.log(childInstance.nonexistentProp);
// 首先在childInstance自身属性中查找,未找到
// 然后在Child.prototype中查找,未找到
// 接着在Parent.prototype中查找,未找到
// 最后在Object.prototype中查找,未找到,返回undefined