当前位置: 首页 > Web前端 > JavaScript

javascript_0

时间:2023-03-27 18:35:59 JavaScript

js中this的方向比较绕,可能跟其他语言不一样。很多资料中举的例子也很绕。这里自己做个记录,方便大家牢记:leta={a:1,check:function(){//Thishere指向对象a;console.log('检查:',this);//匿名函数function()将引发this指向窗口letb=function(){console.log('b:',this)};b();//这里是ec最新的箭头函数,箭头函数是没有this的,这里的this是外层传入的this,也是check函数的this;让c=()=>{console.log('c:',this)};C();}};functionoutfun(){console.log('outfun:',this);}//调用函数a.check();outfun();//结果检查:{a:1,check:?}b:Window{0:global,window:Window,self:Window,document:document,name:'',location:Location,...}c:{a:1,check:?}outfun:Window{0:global,window:window,self:Window,document:document,name:'',location:Location,...}解释:1.function()函数的this指向外层this。这取决于外层是什么。如果它在对象内部,则可能是整个对象。如果是全局函数,可能是window。2.匿名函数this指向window或undefined(typescript严格模式)