function exampleFunction(){
var theVariable = "Lol!";
var variable2 = Lol.toLowerCase();
console.log(theVariable);
delete theVariable; //to prevent bugs, I want to ensure that this variable is never used from this point onward.
console.log(theVariable); //This still prints "Lol!", even though I just tried to delete the variable.
}
Run Code Online (Sandbox Code Playgroud)
在JavaScript中,是否可以防止变量在某个点之后在函数中使用?我已经尝试声明一个名为的字符串theVariable,然后我尝试使用删除变量delete theVariable,但即使在那之后console.log(theVariable)仍然打印出来theVariable的值.
我试着使用delete theVariable,使theVariable从该点以后不可用(为了防止自己不小心使用时不再需要它的变量),但它不会出现有这种效果.有没有办法解决这个限制?
一种方法是限制其范围.由于JavaScript没有块范围,因此需要IIFE(或类似技术):
function exampleFunction(){
var variable2;
(function() {
var theVariable = "Lol!";
variable2 = Lol.toLowerCase();
console.log(theVariable);
})();
// theVariable is now out of scope, and cannot be referenced
}
Run Code Online (Sandbox Code Playgroud)