javascript - 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 个嵌套返回函数到底是什么?
它们究竟是如何工作的?
解决方案
在您的第二个版本中,您在 callfunc
时调用bind()
,并返回函数调用的值。
它正在打印函数的源代码,hello
因为arguments
它是类似数组的对象[person.hello, person]
,因此您有效地进行了调用person.hello(person.hello, person)
,并且 this 设置thing
为person.hello
,并将函数转换为字符串以进行连接返回其源代码。
要绑定一个函数,您必须返回一个可以稍后调用的闭包。这是在您的第一个版本中通过返回一个匿名函数来完成的。
推荐阅读
- ios - IOS Alamofire ssl 固定
- java - 从目标文件到字段的反序列化问题
- swift - 如何在 SwiftUI 中设置图像的宽度和高度?
- c++ - 指针数据类型变量如何包含对象?
- swagger - 如何将 ref 示例与另一个 ref 示例一起使用?
- java - 升级 React Native 0.61.5:Android 卡在闪屏
- aspnetboilerplate - UpdateAsync 期间的 AbpBoilerPlate EF Core 3.0 StackOverflowException
- excel - 如何从列中的所有单元格中删除第二个句号之后的所有文本?
- javascript - Vue,v-bind:将数据作为属性传递
- javascript - 在使用 CORS 的情况下,Edge 浏览器不会重定向呼叫