对比普通函数和箭头函数中的this关键字

128 阅读1分钟

记录一些比较简单易懂的案例来加深对函数中this关键字的理解

  • 普通函数(用function关键字定义的函数)中的this:指向调用该函数的对象
  • 箭头函数中的this:指向箭头函数被“定义”时的上下文
  1. 函数作为简单对象中的方法

    const o = {
      fn: function() {
        console.log(this);
      },
      func: () => {
        this.a = "A";
        console.log(this);
      },
      test: () => {
        console.log(window === this);  // 注意这里window全小写,不要写成Window
    }
    
    o.fn();  // Object { fn: fn(), func: func() }
    o.func();  // Window
    o.test();  // true
    console.log(window.a);  // "A"
    
    • 在这个例子中,箭头函数在被定义的时候,this指向的是window,说明在对象里定义属性时,环境中的this不是指向对象,而是指向window
  2. 函数作为构造函数中的属性(方法)

    function F_obj() {
      this.fn = function() {
        console.log(this);
      };
      this.func = () => {
        console.log(this);
      }
    } 
    
    const f_obj = new F_obj();
    f_obj.fn();  // Object { fn: fn(), func: func() }
    f_obj.func();  // Object { fn: fn(), func: func() }
    
    const new_fn = f_obj.fn;
    const new_func = f_obj.func;
    new_fn();  // Window
    new_func();  // Object { fn: fn(), func: func() }
    
    • 在这个例子中,箭头函数的this在函数被定义的时候就已确定,不会因为后期赋值给其它函数而改变