美文网首页
箭头函数的this

箭头函数的this

作者: 209bd3bc6844 | 来源:发表于2017-05-15 17:36 被阅读0次

    哪些情况不能使用this
    少年,不要滥用箭头函数啊

    箭头函数的this是根据外层(函数或者全局)作用域来决定this,箭头函数会捕捉调用父函数时候父函数的this

    //eg1
    var x = 10;
    var demo2 = {
        x : 1,
        test1 : () => { console.log(this.x); },
    };
    demo2.test1();  // 10
    

    上面代码的结果为什么是10,test1不是在demo2这个对象内吗?所以不应该this就指向demo2了吗?以上代码中,箭头函数中的this并不是指向aa这个对象。对象aa并不能构成一个作用域,所以再往上到达全局作用域,this就指向全局作用域。因为test1没有父函数,直接就是全局作用域。所以这里的this指向window。

    //eg2
    var id = '888'
    var handler = {
      id: '123456',
      init: function() {
         (()=>{
            console.log(this.id)
         })()// 让箭头函数自执行
      },
      init1: function() {
         (function(){
          (()=>{console.log(this.id)})()
         })()  // 匿名函数自执行的内部是箭头函数的自执行
      },
      };
    handler.init()//123456
    var aa = handler.init
    aa() // 888
    handler.init1()//888
    

    eg2的话init创建了一个作用域。箭头函数会捕捉调用init时候init内的this。handler.init调用时候init内的this指向handler对象。var aa = handler.init; aa()这样子的话调用init是window。所以值是888。handler.init1()的值为什么是888呢?因为init1内部是个匿名函数自执行。自执行内部才是箭头函数。所以这样子看来,箭头函数的外部是个匿名函数自执行,而自执行函数的this指向window。所以init1的值为888

    1. 箭头函数适合于无复杂逻辑或者无副作用的纯函数场景下,例如用在map、reduce、filter的回调函数定义中;
    2. 不要在最外层定义箭头函数,因为在函数内部操作this会很容易污染全局作用域。最起码在箭头函数外部包一层普通函数,将this控制在可见的范围内;

    箭头函数的this

    1
     $("#desktop a img").each(function(index){
                alert($(this));
                alert(this);
     }   //这里的this就是 $("#desktop a img").   谁调用就是谁  jquery库把this进行了包装
    2
    $(".myMenuItem").mouseover( () => {
        console.log("$(this)",$(this)) 
    } //这里的$(this)也是jquery对象但是指向整个react ,取决于箭头函数在哪儿定义,而非箭头函数执行的上下文环境。这里相当于也是回调。箭头函数本身是没有this的所以就向上找一层
    

    匿名函数自执行,setTimeout等中的this指向全局

    JavaScript 环境中内置的 setTimeout() 函数实现和下面的伪代码类似:
    function setTimeout(fn,delay) { // 等待 delay 毫秒
      fn(); // <-- 调用位置! 这里就是单纯的函数调用,所以指向全局
    }
    
    function Bue() {
        (function() {
            debugger;
            console.log('this', this.init)   所以这里的this是window this.init为undefined。并不是你所想象的this指向app实例。
        })()
    }
    Bue.prototype.init = 'wo'
    var app = new Bue()
    
    function Bue() {
        console.log('this', this.init) //这里的this指向app。所以可以在Bue中直接使用Bue.prototype上的属性
    }
    Bue.prototype.init = 'wo'
    var app = new Bue() // new的时候会把Bue的上下文换成app实例的执行一遍。所以new Bue()时候可以执行console.log
    

    forEach 中的this

    function hh () {
      [].slice.call(node.childNodes).forEach(_compileNode, this); // 需要传递this
    }
    

    若想._compileNode函数中的this和函数hh的this指向一致,就需要手动给forEach传第二个参数this。

    相关文章

      网友评论

          本文标题:箭头函数的this

          本文链接:https://www.haomeiwen.com/subject/fbbhxxtx.html