What is lexical 'this'?

后端 未结 6 637
臣服心动
臣服心动 2020-11-29 02:46

Could someone please give me a brief introduction to lexical this?

\"An arrow function expression (also known as fat arrow function) has a shorter syn

6条回答
  •  一整个雨季
    2020-11-29 03:49

    Lets say you have a click listener. In that listener you are performing some AJAX operation like setTimeout. After the set time has been reached, the code inside the callback will be executed. Inside that callback you may have accessed this to change the color of the clicked button. But the control will be out of context due to AJAX operation. ES2015 introduced the arrow function to fix that problem. The arrow function captures the this value of the enclosing context.

    The example use-case is:

    $('.btn').click(function () {
        setTimeout(function () {
            $(this).text('new'); 
            // This will cause an error since function() defines this as the global object.
        } ,100); 
    }); 
    

    To avoid this case:

    $('.btn').click(function () { // <- Enclosing context
        setTimeout( () => {
            $(this).text('new')  } 
            // This works, because this will be set to a value captured from the enclosing context.
          ,100);
    });
    

提交回复
热议问题