使用内部函数返回到外部函数的必要性是什么
what's the neccessity of using an inner function to return to the outer function?
>这两个函数有什么区别?
function bind_1(f, o) {
if (f.bind)
return f.bind(o);
else
return function() { return f.apply(o. arguments); };
}
function bind_2(f, o) {
if (f.bind)
return f.bind(o);
else
return f.apply(o. arguments);
}
Vadim 和 Corbin 基本上都是正确的,但要添加一点特异性和冗长性(我说的是大词(,bind_1返回一个函数,该函数将始终调用给定函数 (f(,并将给定参数 (o( 设置为上下文 - 设置上下文意味着在函数内部,this 关键字将引用分配的上下文对象。而bind_2将返回:具有上下文 (o( 的函数 (f(,或返回使用上下文 (o( 调用函数 (f( 的结果。
Function.prototype.bind 也可用于部分函数应用。例如,如果您不关心在函数中使用上下文,则可以为函数提供已应用参数的函数,从而简化后续调用:
// define a function which expects three arguments
function doSomething (person, action, message) {
return person + " " + action + " " + message + ".";
}
var shortcut = doSomething.bind(null, "Joshua", "says");
// the call to bind here returns a function based on doSomething with some changes:
// 1. the context (_this_) is set to null
// 2. the arguments (person and action) are defined ("Joshua" and "says") and not changeable
// now we can use shortcut("Hello")
// instead of doSomething("Joshua", "says", "Hello")
shortcut("Hello"); // returns "Joshua says Hello."
传递给 .apply((、.call(( 或 .bind(( 的第一个参数正在更改函数/方法的上下文。上下文是 this 关键字的值;因此,在函数内部,此值将是作为第一个参数传递的任何值。在这里我使用 null,因为在这种情况下,函数不需要上下文的特定值;null 比未定义的字符少,感觉比一些垃圾值(" - 空字符串,{} - 空对象等(更好。因此,其余两个变量被分配为函数的第一组参数。
function exampleContext () {
return this; // context of function execution
}
exampleContext(); // returns the global scope "window" (in the browser)
var exampleBind = exampleContext.bind(null);
exampleBind(); // returns "null"
var exampleBind = exampleContext.bind("Joshua");
exampleBind(); // returns "Joshua"
var exampleBind = exampleContext.bind({});
exampleBind(); // returns "Object {}""
bind_1返回一个函数,该函数在调用时与o.arguments
一起执行f
。
bind_2立即执行f
与o.arguments
.
至于这种"必要性",我不能立即看到。 在某些上下文中,在某些人的代码中,它显然是有目的的。
在大多数情况下,
这样做是为了将不同的上下文(this
值("附加"到函数。
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 如何在JavaScript中将字符串转换为函数引用
- 用嵌套函数和默认函数定义函数
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 无法导出函数expressjs/requestjs中的变量
- 函数参数中的数据与指定变量之间的任何性能差异
- JQuery合并了keyup和focusout两个函数
- ES6构造函数返回基类的实例
- 监视函数从服务返回不起作用,但作用域函数起作用
- 我可以在json对象中添加一个函数吗
- AngularJS:我可以跳过函数参数回调吗
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- jquery点击函数select&取消选择
- 拨打'父亲'函数形式a'儿童'ReactJS中的组件
- Node.js v6.2.0类扩展不是函数错误
- 比较从函数和生成的日期对象
- 使用内部函数返回到外部函数的必要性是什么
- JavaScript中匿名函数作为包装器的必要性