javascript使用误区(switch、this)

1、switch 语句会使用恒等计算符(===)进行比较:

以下实例由于类型不一致不会执行 alert 弹窗:

1 var x = "10";
2 switch(x) {
3     case 10: alert("Hello");
4 }
2、字符串中使用反斜杠(\)换行,不能直接回车换行。
1 var x = "Hello \
2 World!";

 3. 关于this的指向

function函数中,this对象是在运行时基于函数的执行环境绑定的:在全局函数中,this指向的是window;当函数被作为某个对象的方法调用时,this就等于那个对象

html
<
button id='btn'>按钮</button>
JavaScript
onload=function(){ var btn=getElementById('btn'); btn.onclick=function(){ this.style.color=red;//this指向btn setTimeout(function(){ this.style.color=red;//setTimeout是window的方法,故this指向window },1000) } }

问:上述代码,在setTimeout中使用function函数,this始终指向window,如何解决呢?

  常见的window属性和方法有alter,document,parseInt,setTimeout,setInterval,localtion等等,这些在默认的情况下是省略了window前缀的。

答:箭头函数可解决this执行环境所造成的一些问题

箭头函数中,this是在定义函数时绑定的,不是在执行过程中绑定的。简单的说,函数在定义时,this就继承了定义函数的对象。

JavaScript
onload=function(){ var btn=getElementById('btn'); console.log(this);//window btn.onclick=function(){ console.log(this);//<button ...>...</button> setTimeout(()=>{ this.style.color=red;//this指向button元素 },1000) } }

 

posted @ 2019-03-15 16:36  Embrace_LY  阅读(866)  评论(0编辑  收藏  举报