面试题答案
一键面试1. Child 类的原型链结构分析
Child.prototype
是通过Object.create(Parent.prototype)
创建的。这意味着Child.prototype
的__proto__
指向Parent.prototype
。Child.prototype.constructor
被重新赋值为Child
,以正确指向构造函数。- 当创建
Child
的实例child
时,child.__proto__
指向Child.prototype
,而Child.prototype.__proto__
指向Parent.prototype
,Parent.prototype.__proto__
指向Object.prototype
,最终Object.prototype.__proto__
为null
。 - 所以原型链结构为:
child
->Child.prototype
->Parent.prototype
->Object.prototype
->null
。
2. 执行 let child = new Child(); let func = outerFunction(); func(child);
每一步解释
let child = new Child();
:new Child()
首先创建一个空对象。- 然后
Parent.call(this)
在这个新创建的对象上下文中调用Parent
构造函数。在Parent
构造函数中,privateVar
作为局部变量被声明并赋值为10
,同时给新对象添加了getPrivateVar
方法。这个方法可以访问Parent
函数作用域内的privateVar
,因为函数闭包的特性,即使Parent
函数执行完毕,privateVar
依然存在于内存中,并且可以被getPrivateVar
访问。 - 最后,新创建的对象(即
child
)的__proto__
指向Child.prototype
,完成Child
实例的创建。
let func = outerFunction();
:outerFunction
被调用,声明了局部变量closureVar
并赋值为20
。- 然后返回
innerFunction
。innerFunction
形成了一个闭包,它可以访问outerFunction
作用域内的closureVar
。即使outerFunction
执行完毕,closureVar
依然存在于内存中,因为innerFunction
对它的引用。
func(child);
:func
是innerFunction
,当调用func(child)
时,innerFunction
中的console.log(childInstance.getPrivateVar());
执行。这里childInstance
就是child
,child.getPrivateVar()
方法被调用,由于闭包,它可以访问到Parent
函数作用域内的privateVar
,并返回10
打印出来。- 接着
console.log(closureVar);
执行,由于闭包,innerFunction
可以访问到outerFunction
作用域内的closureVar
,并打印出20
。