js中this的指向问题归纳总结
前言
js中this指向问题是个老生常谈的问题了,下面这篇文章再来给大家介绍下,大家可以看看,更深入的了解了解,下面话不多说了,来一起看看详细的介绍吧
this
this:上下文,会根据执行环境变化而发生指向的改变.
1.单独的this,指向的是window这个对象
alert(this);//this->window
2.全局函数中的this
functiondemo(){ alert(this);//this->window } demo();
在严格模式下,this是undefined.
functiondemo(){ 'usestrict'; alert(this);//undefined } demo();
3.函数调用的时候,前面加上new关键字
所谓构造函数,就是通过这个函数生成一个新对象,这时,this就指向这个对象。
functiondemo(){ //alert(this);//this->object this.testStr='thisisatest'; } leta=newdemo(); alert(a.testStr);//'thisisatest'
4.用call与apply的方式调用函数
functiondemo(){ alert(this); } demo.call('abc');//abc demo.call(null);//this->window demo.call(undefined);//this->window
5.定时器中的this,指向的是window
setTimeout(function(){ alert(this);//this->window,严格模式也是指向window },500)
6.元素绑定事件,事件触发后,执行的函数中的this,指向的是当前元素
window.onload=function(){ let$btn=document.getElementById('btn'); $btn.onclick=function(){ alert(this);//this->当前触发 } }
7.函数调用时如果绑定了bind,那么函数中的this指向了bind中绑定的元素
window.onload=function(){ let$btn=document.getElementById('btn'); $btn.addEventListener('click',function(){ alert(this);//window }.bind(window)) }
8.对象中的方法,该方法被哪个对象调用了,那么方法中的this就指向该对象
letname='finget' letobj={ name:'FinGet', getName:function(){ alert(this.name); } } obj.getName();//FinGet ---------------------------分割线---------------------------- letfn=obj.getName; fn();//fingetthis->window
腾讯笔试题
varx=20; vara={ x:15, fn:function(){ varx=30; returnfunction(){ returnthis.x } } } console.log(a.fn()); console.log((a.fn())()); console.log(a.fn()()); console.log(a.fn()()==(a.fn())()); console.log(a.fn().call(this)); console.log(a.fn().call(a));
答案
1.console.log(a.fn());
对象调用方法,返回了一个方法。
#function(){returnthis.x}
2.console.log((a.fn())());
a.fn()返回的是一个函数,()()这是自执行表达式。this->window
#20
3.console.log(a.fn()());
a.fn()相当于在全局定义了一个函数,然后再自己调用执行。this->window
#20
4.console.log(a.fn()()==(a.fn())());
#true
5.console.log(a.fn().call(this));
这段代码在全局环境中执行,this->window
#20
6.console.log(a.fn().call(a));
this->a
#15
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。