我有以下部分代码:
var person = {
name: "Brendan Eich",
hello: function(thing) {
console.log(this.name + " says hello " + thing);
}
}
var bind = function(func, thisValue) {
return function() {
return func.apply(thisValue, arguments);
}
}
var boundHello = bind(person.hello, person);
boundHello("world") // "Brendan Eich says hello world"
这里,代码将在控制台中打印出文本
Brendan Eich says hello world
如果我接受绑定(bind)变量赋值并将其更改为:
var person = {
name: "Brendan Eich",
hello: function(thing) {
console.log(this.name + " says hello " + thing);
}
}
var bind = function(func, thisValue) {
return func.apply(thisValue, arguments);
}
var boundHello = bind(person.hello, person);
boundHello("world") // "Brendan Eich says hello world"
那么结果就是
Brendan Eich says hello function(thing) { console.log(this.name + " says hello " + thing); }
有人可以解释一下为什么会发生这种情况,以及 bind 函数内的 2 个嵌套 return 函数到底是什么?
它们到底是如何工作的?
最佳答案
在第二个版本中,当您调用 bind()
时,您将调用 func
,并返回函数调用的值。
它正在打印 hello
函数的源代码,因为 arguments
是类似数组的对象 [person.hello, person]
,所以您实际上正在调用 person.hello(person.hello, person)
,这会将 thing
设置为 person.hello
,并转换用于连接字符串的函数返回其源代码。
要绑定(bind)一个函数,您必须返回一个可以稍后调用的闭包。这是通过返回匿名函数在您的第一个版本中完成的。
关于Javascript 函数调用和绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54795481/