zoukankan      html  css  js  c++  java
  • 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) } }
  • 相关阅读:
    Android Service 服务(一)—— Service
    ostringstream的使用方法
    【Android动画】之Tween动画 (渐变、缩放、位移、旋转)
    #pragma comment
    添加PDF文件对照度的粗浅原理,及方法
    Jenkins(二)
    “简密”App Store处女作开发总结
    Windows下FFmpeg高速入门
    Storm-0.9.2-incubating源代码编译打包
    几种开源分词工具的比較
  • 原文地址:https://www.cnblogs.com/embrace-ly/p/10537988.html
Copyright © 2011-2022 走看看