gpt4 book ai didi

javascript - 嵌套 .bind 未按预期工作

转载 作者:行者123 更新时间:2023-11-30 08:01:33 25 4
gpt4 key购买 nike

不幸的是,.bind 在创建更复杂的闭包时一直让我很伤心。

我对嵌套函数后 .bind 的工作方式似乎有所不同的原因很感兴趣。

例如:

function t(){
t = t.bind({}); //correctly assigns *this* to t
function nested_t(){
nested_t = nested_t.bind({}); // fails to assign *this* to nested_t
return nested_t;
}
return nested_t();
}
//CASE ONE
alert(t());
// alerts the whole function t instead of nested_t

//CASE TWO
aleft(t.call(t));
// alerts the global object (window)

在这两种情况下,我都期待这样的行为:

function t(){
var nested_t = function nested_t(){
return this;
};
return nested_t.call(nested_t);
}

alert(t.call(t));

如果有人能解释第一种(和/或)第二种情况下 .bind 的行为,我们将不胜感激!

最佳答案

因此,我不会在这里完全重现您的问题(两种情况都返回全局对象),但我会尝试解释我所看到的代码。

function t(){
t = t.bind({}); //correctly assigns *this* to t
function nested_t(){
nested_t = nested_t.bind({}); // fails to assign *this* to nested_t
return this;
}
return nested_t();
}
//CASE ONE
alert(t());

让我们一步一步来。

首先,定义函数t()。然后,调用 时,它会被干净的上下文覆盖。但是,我没有看到此上下文的任何用法。

现在,定义了一个嵌套函数 (nested_t)。 调用时,它会被干净的上下文覆盖。然后它返回它在被调用时拥有的上下文

回到t()。然后返回 nested_t()结果不是 nested_t 本身。在原始函数调用中,nested_t 仍在使用全局上下文进行调用。

因此,当您运行 t() 时,它会返回全局对象。

关于javascript - 嵌套 .bind 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26903358/

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