面试题答案
一键面试func1
函数中的this
:this
的值为obj
。- 原因:在JavaScript中,当函数作为对象的方法被调用时,
this
会指向该对象。这里func1
是obj
的方法,通过obj.func1()
调用,所以this
指向obj
。
innerFunc1
函数中的this
:this
的值为window
(在浏览器环境下,在严格模式下为undefined
)。- 原因:
innerFunc1
是一个普通函数,当它被调用时,this
的指向取决于函数的调用方式。这里它不是作为某个对象的方法调用,而是直接调用,所以在非严格模式下,this
指向全局对象window
,在严格模式下,this
为undefined
。
innerArrowFunc1
箭头函数中的this
:this
的值为obj
。- 原因:箭头函数没有自己的
this
,它的this
继承自外层作用域。这里外层作用域是func1
,func1
中的this
指向obj
,所以箭头函数innerArrowFunc1
中的this
也指向obj
。