Javascript “如何”;这";关键字在常规函数v/s箭头函数中工作
我是Javascript新手,请帮助我理解“this”关键字的意义。 我在下面的代码片段中的每个Javascript “如何”;这";关键字在常规函数v/s箭头函数中工作,javascript,function,ecmascript-6,this,arrow-functions,Javascript,Function,Ecmascript 6,This,Arrow Functions,我是Javascript新手,请帮助我理解“this”关键字的意义。 我在下面的代码片段中的每个console.log()语句前面添加了注释,这些是我的问题/疑问 这是我的代码: var parentObj = { aa : 87, bb : 11, childObj : { a : 12, b : 1122, fun1 : function(){console.log(this)}, // this is method() so here "this" will
console.log()
语句前面添加了注释,这些是我的问题/疑问
这是我的代码:
var parentObj = {
aa : 87,
bb : 11,
childObj : {
a : 12,
b : 1122,
fun1 : function(){console.log(this)}, // this is method() so here "this" will point to our "childObj"
fun2 : ()=>{console.log(this)}, //this Fat Arrow function is pointing to "window(global)" object why?
fun3 : function(){
var innerFunc1 = ()=>{ console.log(this)} // this Fat Arrow function is pointing to "childObj" object why?
innerFunc1();
function innerFunc2(){console.log(this)} // this regular function is pointing to "window(global)" object why?
innerFunc2()
}
}
}
parentObj.childObj.fun1();
parentObj.childObj.fun2();
parentObj.childObj.fun3();
这是我得到的输出:
箭头函数的
此
继承自外部作用域。在非严格模式下,顶层的此
为窗口
,这解释了fun2
。函数
的此
取自其调用上下文(调用函数的对象,如果有的话)innerFunc2
在没有调用上下文的情况下被调用,因此此
是全局对象。对于fun1
和fun3
,this
指的是childObj
,因为调用函数的对象是hanks,@CertainPerformance这确实很有帮助。