使用内部函数返回到外部函数的必要性是什么

what's the neccessity of using an inner function to return to the outer function?

本文关键字:函数 必要性 是什么 外部 内部函数 返回      更新时间:2023-09-26

>这两个函数有什么区别?

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立即执行fo.arguments.

至于这种"必要性",我不能立即看到。 在某些上下文中,在某些人的代码中,它显然是有目的的。

在大多数情况下,

这样做是为了将不同的上下文(this值("附加"到函数。