What is lexical 'this'?

后端 未结 6 648
臣服心动
臣服心动 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:46

    Using this in es6 fat arrow function, makes this to have lexical scope in the sense that what this refers to in that particular scope is assigned to it, unlike the normal es5 function declaration which keeps checking for what this is referenced to starting from the innermost scope to the global scope till it finds it.

    function foo() {
    setTimeout(() => {
        // `this` here is lexically adopted from `foo()`
        console.log( this.a );
    },100);
    }
    var obj = {
      a:2
    };
    foo.call(obj); //2
    

    Meanwhile, pre es6, there was a way to implement lexical scoping in javascript, by assigning a this keyword to a variable, which to an extent makes this local to the scope

    function foo() {
    var self = this; // lexical capture of `this`
    setTimeout( function(){
        console.log( self.a );
    }, 100 );
    }
    var obj = {
      a: 2;
    };
    foo.call(obj); //2
    

提交回复
热议问题