我想重用功能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'
最佳答案
我不确定您为什么特别想要闭包,但是通过查看您的示例,似乎绑定比闭包更合适。
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'