Javascript 函数调用和绑定(bind)

标签 javascript function binding method-invocation

我有以下部分代码:

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/

相关文章:

javascript - 如何向列表中的每个元素逐一添加类

python - Python 函数中 Print 和 Return 的不同输出

wordpress - WordPress:自动在帖子中添加来自YouTube视频的图像

angularjs - ng-repeat 显示模型但不更新它

javascript - 使用可折叠物时 Bootstrap 和 JQuery 的正确调用顺序

javascript - 我怎样才能让我的 JavaScript(如果它是正确的)在倒计时后执行?

javascript - Extjs,折叠表单面板。标题不显示

javascript - 函数内的函数没有被执行

c++ - 无法使用bindgen进行llvm绑定(bind)

c# - 按下按钮时绑定(bind)(显式绑定(bind))始终将 BindingExpression 设置为 null?