gpt4 book ai didi

JavaScript curry : context in returned function

转载 作者:行者123 更新时间:2023-11-28 02:29:56 25 4
gpt4 key购买 nike

在像这样的柯里函数中:

var curry = function() {
var slice = Array.prototype.slice,
args = slice.call(arguments),
fn = args.shift();

return function(){
return fn.apply(null, args.concat(slice.call(arguments)));
};
};

fn.apply 中的 thisnull 有什么区别吗?我不认为它会产生影响。

<小时/>

编辑:

感谢this answer我想现在已经很清楚了,这是我为了理解它而做的一个小例子:

function msg() {
console.log(this.name);
}

var foo = { name: "foo"};

var msg_this = curry_this(msg);
var msg_null = curry_null(msg);

msg_this(); //msg.call(null) -> undefined
msg_null(); //msg.call(null) -> undefined
msg_this.call(foo); //msg.call(foo) -> foo
msg_null.call(foo); //msg.call(null) -> undefined

其中 curry_this 返回 fn.apply(this,...curry_null 返回 fn.apply(null...

最佳答案

null 传递给 apply 会使上下文成为全局上下文(浏览器中的 window)。

来自the MDN :

if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.

这将如何影响结果取决于 fn 函数(curry 的第一个参数)以及您如何调用它。

查看此代码:

var a = {curried: curry(function(){console.log(this)})};
a.curried();

如果您传递 null 来应用,它会记录 window 而不是对象 a

关于JavaScript curry : context in returned function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14378426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com