gpt4 book ai didi

javascript - 括号中带有 "this.variable"的立即调用函数表达式

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

为什么要声明一个立即调用的函数定义,然后在末尾的另一个括号中使用“this.variable”,也许作为参数?该代码给出的结果为“星期六”,但您能解释一下该代码的工作原理吗?

(function(exports) {
var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"];

exports.name = function(number) {
return names[number];
};
exports.number = function(name) {
return names.indexOf(name);
};
})(this.weekDay = {});

console.log(weekDay.name(weekDay.number("Saturday")));
// → Saturday

最佳答案

也许这样你会更容易理解。

(function() { // an object for my this, rather than the global this

function iife(exports) {
// only accessible within the iife context
var names = [
'Sunday', // index number 0
'Monday', // 1
'Tuesday', // 2
'Wednesday', // 3
'Thursday', // 4
'Friday', // 5
'Saturday' // 6
];

// assign property name to the exports object with function as value
exports.name = function(number) {
return names[number];
};

// assign property number to the exports object with function as value
exports.number = function(name) {
return names.indexOf(name);
};
}

// assign property weekDay to the this object with object as value
this.weekDay = {};
// call iife with the first argument as our object's reference
iife(this.weekDay);

// we can see weekDay on our this object with the assigned properties
console.log(this);

// call the number function on the weekDay namespace
// If we had access to names: names.indexOf('Saturday') -> 6
var dayNumber = this.weekDay.number('Saturday');
console.log(dayNumber);

// call the name function on the weekDay namespace
// If we had access to names: names[6] -> 'Saturday'
var dayName = this.weekDay.name(dayNumber);
console.log(dayName);

}).call({}); // make my this object

关于javascript - 括号中带有 "this.variable"的立即调用函数表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749361/

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