gpt4 book ai didi

javascript - 如何使用不同的变量重用闭包

转载 作者:行者123 更新时间:2023-11-28 18:30:24 26 4
gpt4 key购买 nike

我想重用 sayMyName 函数,但使用不同的变量。如果我的构建方式错误,请告诉我,以及我正在尝试做什么的最佳实践是什么。

var sayMyName = function(myName) {
console.log(myName)
};

var name1 = function() {
// myName should not be a global variable
// because there may be more variables/functions
// that I'd want to closed inside sayMyName().
// Declaring all of them to the global scope is not ideal.
var myName = 'Walter';

sayMyName();
// I don't want to pass in myName as argument like this:
// sayMyName(myName);
// I want myName to be implicitly included in sayMyName()
// I want to pass in everything that is declared in name1 to sayMyName() implicitly.
};

var name2 = function() {
var myName = 'White';
sayMyName();
}

name1(); // should give me 'Walter'
name2(); // should give me 'White'

最佳答案

我不确定为什么你特别想要一个闭包,但通过查看你的示例,似乎绑定(bind)比闭包更合适。

var sayMyName = function(myName) {
console.log(myName)
};

var name1 = sayMyName.bind(undefined, 'Walter');
var name2 = sayMyName.bind(undefined, 'White');

name1(); // log 'Walter'
name2(); // log 'White'

关于javascript - 如何使用不同的变量重用闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38135083/

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