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

标签 javascript

这两个函数有什么区别?

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 关键字的值;因此,在函数内部,this 值将是作为第一个参数传递的值。这里我使用了null,因为在这种情况下,函数不需要上下文的特定值; nullundefined 更少的字符,并且比一些垃圾值(“” - 空字符串,{} - 空对象等)感觉更好。因此剩下的两个变量被分配为函数的第一组参数。

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 {}""

关于javascript - 使用内部函数返回外部函数的必要性是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10562269/

相关文章:

javascript - Firefox 不接受我在带有图像的 div 上的宽度和高度规范

javascript - 根据用户ID隐藏div?

javascript - 如何在 Javascript 中克隆 XML 文档?

javascript - 处理两个或多个相同指令的点击离开

javascript - 使用 findIndex() 从非零元素开始

javascript - 是否可以将字体图标转换回其私有(private)使用代码?

javascript - 如何监听特定 HTML 元素的布局变化?

javascript - Web Audio API 过滤器在 Safari 中不起作用

javascript - 单击链接时,AngularJs Controller 不会被调用

javascript - 在 iOS 4 的 UIWebView 中使用 javascript 进行重定向