js 函数调用中的this
Opened this issue · 4 comments
Draymonders commented
Draymonders commented
在调用fn(...args)
就是在调用fn.call(window [ES5-strict: undefined], ...args)
Draymonders commented
对象调用
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
但是下面这个可以看出,我们其实有时候希望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
因此 es5
实现了bind
方法
var boundHello = person.hello.bind(person);
boundHello("world") // "Brendan Eich says hello world"
这样 就不是默认的window
对象在调用了