首页 > 其他 > 详细

ES6箭头函数(二)-this绑定

时间:2021-01-18 16:38:56      阅读:27      评论:0      收藏:0      [点我收藏+]

原文链接

箭头函数,除了帮助我们简写之外,最大的好处就是this不再被绑定在调用者,而是继承与环境对象,在哪个环境定义,this就是指的哪个环境对象。

在编写构造函数或者函数时,this的指向经常会变化,导致this.属性无法在各个函数体面使用

案例代码:

  1.  
       function Counter() {
  2.  
           console.log(‘我是构造体‘+this);
  3.  
           this.number = 0;
  4.  
    ?
  5.  
           //返回一个 ID(数字),可以将这个ID传递给 clearTimeout() 来取消执行。        
  6.  
           this.timer = window.setTimeout(function () {
  7.  
               this.number++;
  8.  
               //此时的this的意思是window,window是没有number属性的
  9.  
               console.log(this.number);
  10.  
          },1000)
  11.  
      }
  12.  
    ?
  13.  
       var b = new Counter();
  14.  
       console.log(b.number);
  15.  
       结果 0
  16.  
            NaN

为了解决this指向问题,我们可以使用bind来改变,不能使用call,apply

  1.  
       function Counter() {
  2.  
           this.number = 0;
  3.  
           var fn = function () {
  4.  
              this.number++
  5.  
               console.log(this.number);
  6.  
          }
  7.  
           // 不能用call、applay,这两种方法都是立即执行,并且不会循环执行
  8.  
           // var timer = window.setTimeout(fn.call(this),3000)
  9.  
           //var timer = window.setInterval(fn.apply(this),3000)
  10.  
           var timer =  window.setInterval(fn.bind(this),3000)
  11.  
      }
  12.  
    ?
  13.  
       var b = new Counter();
  14.  
       console.log(b.number);

从上可以看出,想改变this的指向非常困难

有了箭头函数之后,一切都变得简单,不在绑定this的指向了

  1.  
       function Counter() {
  2.  
           this.number = 0;
  3.  
           var timer = setInterval(() => {
  4.  
               console.log(this);
  5.  
               this.number++;
  6.  
               console.log(this.number);
  7.  
          },2000)
  8.  
      }
  9.  
    ?
  10.  
       var b = new Counter();

原理分析:

普通函数,this的概念是:this是JavaScript的一个关键字,他是指函数执行过程中,自动生成的一个内部对象,是指当前的对象,只在当前函数内部使用。(this对象是在运行时基于函数的执行环境绑定的:在全局函数中,this指向的是window;当函数被作为某个对象的方法调用时,this就等于那个对象)。

 

函数中this对象的取值,是在函数被调用执行的时候确定的。此时会创建执行上下文环境。

对于箭头函数,它没有自己的this,不能用作构造函数。

箭头函数中的this对象是定义时所在的对象,不是调用时所在的对象。

案例1

  1.  
       var testObject = {
  2.  
           name:‘123‘,
  3.  
           sayHi:function () {
  4.  
               console.log(this);
  5.  
               // return function () {
  6.  
               //     console.log(this);
  7.  
               // }
  8.  
               //箭头函数的this,不再是谁调用就是谁,而是指当前环境的this是谁,
  9.  
    //一般是指父级,因为箭头函数没有this对象,都是从父级继承过来的
  10.  
               return ()=>{
  11.  
                   console.log(this);
  12.  
              }
  13.  
          }
  14.  
      }
  15.  
    ?
  16.  
       var hh = testObject.sayHi();
  17.  
       window.hh();

案例2

  1.  
       function foo() {
  2.  
           setTimeout(function() {
  3.  
               console.log(‘setTimeout普通函数的this=‘+this);
  4.  
               console.log("id: ",this.id);
  5.  
          }, 100);
  6.  
      }
  7.  
       function fooa() {
  8.  
           setTimeout(()=>{
  9.  
               console.log(‘setTimeout箭头函数的this=‘+this);
  10.  
               console.log("id: ",this.id);
  11.  
          }, 100);
  12.  
      }
  13.  
       var id=21;
  14.  
       //两个函数的结果都是一样的:window,21
  15.  
       //因为可以理解为都是由window调用的window.foo() 和 window.fooa()
  16.  
       foo();  //this指向window对象, 21
  17.  
       fooa(); //this指向window对象, 21
  18.  
    ?
  19.  
       =========================================
  20.  
       //setTimeout(普通函数体)的this指向的调用时对象,那么这个对象如果不改变的话永远都是window.
  21.  
       foo.call({id:42}); //this指向window对象, 21
  22.  
      //setTimeout(箭头函数体)本身没有this,定义时对象,也就是哪个对象调用了,this就是哪个对象的
  23.  
       fooa.call({id:42}); //this指向object对象, 42
  24.  
    ?

案例3-返回值是函数的,函数体里面的this指向的是window,和普通函数里面的this一样

  1.  
    const test = {
  2.  
     name: ‘test object‘,
  3.  
     createAnonFunction: function() {
  4.  
       return function() {
  5.  
         //function 当做了普通函数,this的指向是window
  6.  
         console.log(this.name);
  7.  
         console.log(arguments);
  8.  
      };
  9.  
    },
  10.  
     
  11.  
     createArrowFunction: function() {
  12.  
       return () => {
  13.  
         //箭头函数本身没有this对象,this是在定义是去找,本身没有的话,就会去父级寻找
  14.  
         //当test对象去调用方法createArrowFunction,this就获得了test对象
  15.  
         console.log(this.name);
  16.  
         console.log(arguments);
  17.  
      };
  18.  
    }
  19.  
    };
  20.  
    //结果
  21.  
    JavaScript 代码:
  22.  
    > const anon = test.createAnonFunction(‘hello‘, ‘world‘);
  23.  
    > const arrow = test.createArrowFunction(‘hello‘, ‘world‘);
  24.  
     
  25.  
    > anon();
  26.  
    undefined
  27.  
    {}
  28.  
     
  29.  
    > arrow();
  30.  
    test object
  31.  
    { ‘0‘: ‘hello‘, ‘1‘: ‘world‘ }

案例4-函数作为参数的时候,函数体里面的this指向的是window,和普通函数里面的this一样

  1.  
       Array.prototype.myFind = function (index,callback) {
  2.  
           //this是对象数组
  3.  
           console.log(this)
  4.  
           for (var i = 0; i < this.length; i++) {
  5.  
               if(i === index){
  6.  
                   callback(this[i])
  7.  
              }
  8.  
          }
  9.  
      }
  10.  
       var arr = [‘hello‘, ‘WORLD‘, ‘Whatever‘];
  11.  
       arr.myFind(1,function (item) {
  12.  
           //this是window
  13.  
           console.log(this);
  14.  
           console.log(item);
  15.  
      })
特殊的案例
  1.  
    Array.prototype.myFind = function (index, callback) {
  2.  
    ?
  3.  
           for (var i = 0; i < this.length; i++) {
  4.  
               if (i === index) {
  5.  
                   callback.call(this,this[i])
  6.  
                   //callback(this[i])
  7.  
              }
  8.  
          }
  9.  
      }
  10.  
     
  11.  
       var arr = [‘hello‘, ‘WORLD‘, ‘Whatever‘];
  12.  
       arr.myFind(1, function (item) {
  13.  
           //array数组
  14.  
           console.log(this);
  15.  
    ?
  16.  
      })
  17.  
    ?
  18.  
       arr.myFind(1, item => {
  19.  
           //window对象
  20.  
           console.log(this);
  21.  
      })

ES6箭头函数(二)-this绑定

原文:https://www.cnblogs.com/MoonASixpence/p/14292960.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!