• JavaScript this指向问题总结


    一、谁调用this this就指向谁(ES6 箭头函数除外)

      Demo 1   全局作用域内调用函数,this就指向window

      function fn()  {  
        console.log(this) 
      }
      fn();     //window
      window.fn();      //window
      //注意 全局定义的变量函数等..其实都是在window对象下新增的属性

      Demo 2  this永远指向的是最后调用它的对象  

        var obj = {
          user:"zhangsan",
          age:20,
          fn:function(){
            console.log(this); //{user: "zhangsan", age: 20, fn: ƒ}
          }
        }
        window.obj.fn();

      Demo 3  通过事件来调用函数,this就指向这个事件的调用者

      <button id="btn">按钮</button>
      <script>
              var btn=document.getElementById('btn');
              btn.addEventListener('click',function(){
                  console.log(this)    //<button id="btn">按钮</button>
              })
      </script>

       Demo 4  通过对象来调用对象里面的函数,this就指向这个对象

        var obj={
          name:"zhangsan",
          age:20,
          say:function(){
            console.log(this)   //{name: "zhangsan", age: 20, say: ƒ}
          }
        }
        obj.say();

       Demo 5  通过构造函数来实例化的对象中的this,指向这个实例化对象

        function Fn(){
          this.name="zhangsan"
          this.age=20
          console.log(this)   //Fn {name: "zhangsan", age: 20}
        }
        var user=new Fn()

    二、ES6 箭头函数

      箭头函数里的this指的是定义时所在的作用域,而不是运行时所在的作用域(箭头函数的 this 永远指向该函数构造时的环境)

        //不使用箭头函数
        var obj1 = {   
          name: "zhangsan",
          age:20,
          test: function(){   //{name: "zhangsan", age: 20, test: ƒ} 普通函数中的this表示调用此函数时的对象
            console.log(this)
          }
        }
        obj1.test();
        // 使用箭头函数
        var obj = {
          name: "zhangsan",
          age:20,
          test: () => console.log(this)    //window  这是为什么呢  因为 箭头函数里面的this会继承自外部的this
        }
        obj.test();
     注意:如果还不明白请看下面例子
      
        var obj={
          name:"zhangsan",
          age:20,
          there:this,    //这个this 指的是 window 
          say:()=>{
            console.log(this)   //window  箭头函数的this 继承函数外部的this
          }
        }
        obj.say()   //window
        console.log(obj.there)   //window

      箭头函数总结:箭头函数并不是用来替代普通函数的,如果在箭头函数中使用this当前调用者的this就没有必要使用箭头函数。



      

  • 相关阅读:
    目标跟踪的评价指标
    [c++] stringstream的用法
    [OpenCV] sift demo
    [TCP/IP] 滑动窗口
    [python] 一行命令搭建http服务内网传文件
    YII 获取系统级请求参数的常用方法
    windows系统npm如何升级自身
    修补--Redis未授权访问漏洞
    MySQL中的两个时间函数,用来做两个时间之间的对比
    Centos 安装mongodb
  • 原文地址:https://www.cnblogs.com/banyuege/p/10722351.html
Copyright © 2020-2023  润新知