js 函数中的this

资料

function 函数

没有“this”的持久概念, 调用函数时,创建this

function hello(thing) {
  console.log(this + " says hello " + thing);
}

person = { name: "Brendan Eich" }
person.hello = hello;

// 在person中调用 hello, this被创建到了person
person.hello("world") // still desugars to person.hello.call(person, "world")

// 在window中调用 this被创建到了 window
hello("world") // "[object DOMWindow]world"

引用具有持久this值的函数

name = "global";

var person = {
  name: "Brendan Eich",
  hello: function() {
    console.log(this.name);
  }
};

var boundHello = function(arguments) {
  return person.hello.apply(person, arguments);
};
boundHello(); // Brendan Eich

let a = person.hello.bind(person);
a(); // Brendan Eich

let b = person.hello
b() // global

箭头函数

箭头函数捕获this => 创建函数的位置 而不是调用它的位置

箭头函数没有自己的this, 箭头函数内部的上下文在函数的整个生命周期中保持不变, 并且始终将this绑定到最接近的非箭头父函数中的上下文

let o = {
  a: 'ajanuw',
  hello: function(){
    //  返回箭头函数时,this已经被绑定了
    return () => {
      console.log(this.a)
    }
  }
}

let a = o.hello()
a()