返回列表 发帖

[问题求助] js闭包怎么返回一个构造函数

网上搜到的闭包都是返回一个正常的函数
但是我想要返回一个类或者构造函数怎么办?
对象赋值到变量都是传址的
这样行吗?
function s(){
var div_count=0;
return(class{
constructor(){
alert(1);
}
});
}COPY
你好

本帖最后由 老刘1号 于 2023-3-5 22:29 编辑

多层套娃似神仙
function s(){
var div_count=0;
return (function() {;
div_count ++;
var obj = {'cnt' : div_count};
return obj;
});
}
cnt1 = s();
cnt2 = s();
console.log(cnt1());
console.log(cnt1());
console.log(cnt1());
console.log(cnt2());COPY
当然更离谱的套娃也有,比如匿名函数实现递归的Y组合子
var fn = f => n => n ? f(n-1)*n : 1;
var Y = y => (x => y(n => x(x)(n)))(x => y(n => x(x)(n)));
alert(Y(fn)(4));COPY

TOP

返回列表