是否可以在 JavaScript 中编写连续的嵌套函数? [英] Is it possible to write continuous nested functions in JavaScript?
本文介绍了是否可以在 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 中编写连续的嵌套函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文