【发布时间】:2019-07-14 16:22:41
【问题描述】:
我有以下部分代码:
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); }
谁能解释一下为什么会发生这种情况以及 bind 中的 2 个嵌套 return 函数到底是什么?
它们究竟是如何工作的?
【问题讨论】:
-
当我运行你的第二个例子时,我得到了
uncaught TypeError: boundHello is not a function- 这是我所期望的(但无论如何我都会检查它以防我错过了什么)。不同之处在于bind的第一个(正确)版本返回一个函数——func的一个版本,它始终绑定到thisValue作为其this引用。第二个(不正确的)版本只是立即返回一个(非函数)值(在这种情况下它是undefined,但它通常是func为您提供的参数返回的任何值) - 所以你可以'不叫它。 -
我想我有点明白你所说的无功能是什么意思了。
标签: javascript function binding method-invocation