我想向此代码添加第三个函数:
var fn3 = (function() {
var first = true;
return function() {
first ? fn1() : fn2();
first = !first;
}
})();
function fn1() {
console.log(1);
};
function fn2() {
console.log(2);
};
----
<button onClick="fn3()">click</button>
我尝试添加 fn3()
并将 var 更改为其他内容,但不幸的是,它不起作用。有人可以帮我吗?谢谢:)
最佳答案
您可以将函数存储在数组中,并使用索引来获取下一个函数。
function fn1() {
console.log(1);
}
function fn2() {
console.log(2);
}
function fn3() {
console.log(3);
}
var next = (function(array) {
var index = -1;
return function() {
return array[index = (index + 1) % 3]();
};
})([fn1, fn2, fn3]);
<button onClick="next()">click</button>
关于javascript - 向 IIFE 添加第三个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60619651/