首页 > 解决方案 > Javascript函数调用和绑定

问题描述

我有以下部分代码:

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)说你好,世界

如果我接受绑定变量赋值并将其更改为:

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 打招呼 function(thing) { console.log(this.name + "打招呼" + thing); }

有人可以解释一下为什么会发生这种情况,绑定中的 2 个嵌套返回函数到底是什么?

它们究竟是如何工作的?

标签: javascriptfunctionbindingmethod-invocation

解决方案


在您的第二个版本中,您在 callfunc时调用bind(),并返回函数调用的值。

它正在打印函数的源代码,hello因为arguments它是类似数组的对象[person.hello, person],因此您有效地进行了调用person.hello(person.hello, person),并且 this 设置thingperson.hello,并将函数转换为字符串以进行连接返回其源代码。

要绑定一个函数,您必须返回一个可以稍后调用的闭包。这是在您的第一个版本中通过返回一个匿名函数来完成的。


推荐阅读