问题描述
如何使用IIFE.n()更改s变量,因为现在它不起作用.我执行IIFE.n()之后,IIFE.s仍返回字符串"
How to change the s variable using IIFE.n() because now it doesn't work. After I execute IIFE.n() IIFE.s still returns "string"
我已经尝试过了,但是我宁愿使用let/const,也不希望将此变量传递给全局范围,我想将其保留在模块中.
I've tried with this but I rather use let/const and don't want to pass this variable to global scope I want to keep it in module.
const iife = (() => {
let s = "string";
const n = () => {
s = 1e3;
};
return {
s: s,
n: n
};
})()
当前,当我执行iife.n()时,它不会更改s变量(当我在s = 1e3之前添加return时,它返回1000,但iife.s仍返回字符串")
Currently when I do iife.n() it doesn't change the s variable (when I added return before s = 1e3 it returns 1000 but iife.s still returns "string")
推荐答案
它确实会更改 s
,但是您没有任何方法来获取更新后的值,因此看不到它正在改变.尝试此操作,您将看到更新的 s
:
It does change s
, but you don't have any way to get the updated value, so you can't see that it's changing. Try this and you'll see the updated s
:
const iife = (() => {
let s = "string";
const n = () => {
s = 1e3;
};
const gets = () => s;
return {
s: s,
n: n,
gets: gets
};
})();
iife.n();
console.log(iife.gets());
iife.s
与 s
变量不同.该变量仅用于初始化属性,但并未永久链接.
iife.s
is not the same as the s
variable. The variable was just used to initialize the property, but they're not linked permanently.
这篇关于JS:如何更改函数中的变量(IIFE)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!