箭头函数与this指向探究

简介: 箭头函数与this指向探究

我有明珠一颗,久被尘劳关锁,一朝尘净光生,照破山河万朵。——柴陵郁禅师

今天研究了下箭头函数与this,发现了一些挺好玩的特性

首先,我们在控制台输入上这段js

var handler = {
    name :'handler',
    init: function() {
    let init1 = function(event) {
        console.log("init1: ", this);
        let init5 = function(){
            console.log("init5: ", this);
        }
        init5();    // init5:  Window {window: Window, self: Window, document: document, name: '', location: Location, …}
    };
    init1()    // init1:  Window {window: Window, self: Window, document: document, name: '', location: Location, …} 
    let init2 = () => console.log("init2: ", this);
    init2.call()    // init2:  {name: 'handler', init: ƒ}
    let init3 = () => {
        let init4 = ()=> console.log("init4: ", this);
        init4()    // init4:  {name: 'handler', init: ƒ}
    }
    init3.apply();
  },
};
handler.init();

可以明显的看到,箭头函数是锁定了this指向的,这里的箭头函数中的this都指向这个handler对象

而使用function声明的函数中的this永远指向外部的window对象

我们再到webpack构建的vue项目中尝试

printThis() {
  console.log("printThis", this);   // VueComponent {_uid: 2, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
  function print1() {
    console.log("print1: ", this);    // undefined
    function print2() {
      console.log("print2: ", this);    // undefined
      let print3 = () => void console.log("print3: ", this);    // undefined
      print3.apply()
    }
    print2.call();
    let print4 = () => void console.log("print4: ", this);    // undefined
    print4.apply();
  }
  print1.call();
  let print5 = () => {
    console.log("print5: ", this)   // VueComponent {_uid: 2, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
    let print6 = () => console.log("print6: ", this);   // VueComponent {_uid: 2, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
    print6.call();
  };
  print5();
}

可以看到这里的箭头函数中的this都为undefined

而使用function声明的函数仍然指向当前Vue组件实例

了解这个特性,能清楚this的具体指向,方便后续前端开发

相关文章
|
3月前
箭头函数和普通函数的区别
箭头函数和普通函数的区别
17 0
|
4月前
|
自然语言处理
解释一下箭头函数的this绑定行为。
箭头函数的`this`绑定遵循词法作用域,不同于普通函数的动态绑定。它在定义时即确定,不受调用方式影响。这解决了`this`丢失问题,提供了更简洁的语法。例如,当在一个对象中,箭头函数的`this`将指向全局对象或父级作用域,而不是对象本身,与普通函数表现不同,使用时需谨慎。
33 8
|
4月前
箭头函数需要注意的地方
箭头函数需要注意的地方
24 1
面试官:箭头函数和普通函数的区别?箭头函数的this指向哪里?(二)
面试官:箭头函数和普通函数的区别?箭头函数的this指向哪里?(二)
普通函数中的this指向问题解决方案箭头函数
普通函数中的this指向问题解决方案箭头函数
35 0
|
10月前
|
JavaScript 前端开发
箭头函数和普通函数有什么区别
箭头函数和普通函数有什么区别
51 1
|
JavaScript 前端开发
ES6——箭头函数以及this指向
箭头函数以及this指向
97 0