How to unset a JavaScript variable?

后端 未结 11 2028
执笔经年
执笔经年 2020-11-22 04:16

I have a global variable in JavaScript (actually a window property, but I don\'t think it matters) which was already populated by a previous script but I don\'t

11条回答
  •  抹茶落季
    2020-11-22 05:03

    If you are implicitly declaring the variable without var, the proper way would be to use delete foo.

    However after you delete it, if you try to use this in an operation such as addition a ReferenceError will be thrown because you can't add a string to an undeclared, undefined identifier. Example:

    x = 5;
    delete x
    alert('foo' + x )
    // ReferenceError: x is not defined
    

    It may be safer in some situations to assign it to false, null, or undefined so it's declared and won't throw this type of error.

    foo = false
    

    Note that in ECMAScript null, false, undefined, 0, NaN, or '' would all evaluate to false. Just make sure you dont use the !== operator but instead != when type checking for booleans and you don't want identity checking (so null would == false and false == undefined).

    Also note that delete doesn't "delete" references but just properties directly on the object, e.g.:

    bah = {}, foo = {}; bah.ref = foo;
    
    delete bah.ref;
    alert( [bah.ref, foo ] )
    // ,[object Object] (it deleted the property but not the reference to the other object)
    

    If you have declared a variable with var you can't delete it:

    (function() {
        var x = 5;
        alert(delete x)
        // false
    })();
    

    In Rhino:

    js> var x
    js> delete x
    false
    

    Nor can you delete some predefined properties like Math.PI:

    js> delete Math.PI
    false
    

    There are some odd exceptions to delete as with any language, if you care enough you should read:

    • https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator
    • http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf

提交回复
热议问题