Draymonders / Code-Life

The marathon continues though.
27 stars 3 forks source link

js 函数调用中的this #44

Open Draymonders opened 4 years ago

Draymonders commented 4 years ago
Draymonders commented 4 years ago

在调用fn(...args) 就是在调用fn.call(window [ES5-strict: undefined], ...args)

Draymonders commented 4 years ago

对象调用

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

// this:
person.hello("world")

// desugars to this:
person.hello.call(person, "world");
Draymonders commented 4 years ago

但是下面这个可以看出,我们其实有时候希望this是object 而不是window

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

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

person.hello("world") // still desugars to person.hello.call(person, "world")

hello("world") // "[object DOMWindow]world"
Draymonders commented 4 years ago

因此 es5 实现了bind方法

var boundHello = person.hello.bind(person);
boundHello("world") // "Brendan Eich says hello world"

这样 就不是默认的window对象在调用了