0
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.
}

In JavaScript, is it possible to prevent a variable from being used in a function after a certain point? I've tried declaring a string called theVariable, and then I tried to delete the variable using delete theVariable, but console.log(theVariable) still prints theVariable's value even after that point.

I tried using delete theVariable to make theVariable unusable from that point onward (in order to prevent myself from accidentally using the variable when it is no longer needed), but it doesn't appear to have that effect. Is there any way to work around this limitation?

4

3 回答 3

5

一种方法是限制其范围。由于 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
}
于 2013-06-26T04:02:34.343 回答
2

在这种情况下,您可以将值设置为undefined喜欢theVariable = undefined

删除功能没有按预期工作

来自文档

删除操作符从对象中删除一个属性。

在这种情况下theVariable不是对象的属性,它是当前函数范围内的变量。

于 2013-06-26T04:01:03.943 回答
0

您不能删除原始类型,只能删除对象。如果您不想在某个时间点之后使用变量,只需检查您的代码,以免使用它。不幸的是,JS 没有块作用域来限制变量的可见性。您必须手动检查。

或者,将值设置为未定义。

于 2013-06-26T04:05:47.577 回答