本文介绍了是否可以用JavaScript编写连续的嵌套函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这是闭包的领域,而不是闭包的领域.但是可以连续调用嵌套的匿名函数吗?
I know this is the realm of closures and what not. But is it possible to continuously call nested anonymouse funtions?
说我有这个:
function testing(input) {
var testing = 0;
(function() {
testing = testing + 1;
})()
return "testing";
}
我们可以有这样的东西testing()()()()()()()
吗?
Can we have something like this testing()()()()()()()
?
推荐答案
您可以使用内部函数进行更新,并具有toString
方法来获取原始值.
You could use an inner function which makes the update and has a toString
method to get a primitive value.
function testing() {
function fn() {
string += ++counter;
return fn;
}
var counter = 0,
string = 'foo';
fn.toString = _ => string;
return fn();
}
console.log(testing());
console.log(testing()());
console.log(testing()()());
这篇关于是否可以用JavaScript编写连续的嵌套函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!