谁能解释一下这段基于 IIFE(立即调用的函数表达式)概念的代码的输出
Can anyone explain the output for this code which is based on the concept of IIFE (Immediately Invoked Function Expression)
(function(value){
var names = ["January","February","March","April","May","June","July",
"August","September","October","November","December"];
value.name = function(number){
return names[number];
};
value.number = function(name){
return names.indexOf(name);
};
})(this.month = {});
console.log(month.name(2));
console.log(month.number("November"));
请帮我解释一下这个程序是如何工作的。我不明白为什么要在函数外创建一个新对象以及为什么使用 this 运算符。
this
将是全局对象(因为它没有在函数内部使用)。
this.month = {}
将新对象分配给全局对象上的 month
。
赋值作为分配的值计算,以便传递给函数。
从本质上讲,这只是一种丑陋且不直观的书写方式:
function myFunction(value) {
var names = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
value.name = function(number) {
return names[number];
};
value.number = function(name) {
return names.indexOf(name);
};
}
var month = {};
myFunction(month);
console.log(month.name(2));
console.log(month.number("November"));
它使用 this
因为你不能在用于调用函数的 ()
中使用 var
。
(function(value){
var names = ["January","February","March","April","May","June","July",
"August","September","October","November","December"];
value.name = function(number){
return names[number];
};
value.number = function(name){
return names.indexOf(name);
};
})(this.month = {});
console.log(month.name(2));
console.log(month.number("November"));
请帮我解释一下这个程序是如何工作的。我不明白为什么要在函数外创建一个新对象以及为什么使用 this 运算符。
this
将是全局对象(因为它没有在函数内部使用)。
this.month = {}
将新对象分配给全局对象上的 month
。
赋值作为分配的值计算,以便传递给函数。
从本质上讲,这只是一种丑陋且不直观的书写方式:
function myFunction(value) {
var names = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
value.name = function(number) {
return names[number];
};
value.number = function(name) {
return names.indexOf(name);
};
}
var month = {};
myFunction(month);
console.log(month.name(2));
console.log(month.number("November"));
它使用 this
因为你不能在用于调用函数的 ()
中使用 var
。