How to unset a JavaScript variable?

后端 未结 11 2046
执笔经年
执笔经年 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 04:54

    I am bit confused. If all you are wanting is for a variables value to not pass to another script then there is no need to delete the variable from the scope. Simply nullify the variable then explicit check if it is or is not null. Why go through the trouble of deleting the variable from scope? What purpose does this server that nullifying can not?

    foo = null;
    if(foo === null) or if(foo !== null)
    
    0 讨论(0)
  • 2020-11-22 04:56

    Variables, in contrast with simple properties, have attribute [[Configurable]], meaning impossibility to remove a variable via the delete operator. However there is one execution context on which this rule does not affect. It is the eval context: there [[Configurable]] attribute is not set for variables.

    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-11-22 05:08

    The delete operator removes a property from an object. It cannot remove a variable. So the answer to the question depends on how the global variable or property is defined.

    (1) If it is created with var, it cannot be deleted.

    For example:

    var g_a = 1; //create with var, g_a is a variable 
    delete g_a; //return false
    console.log(g_a); //g_a is still 1
    

    (2) If it is created without var, it can be deleted.

    g_b = 1; //create without var, g_b is a property 
    delete g_b; //return true
    console.log(g_b); //error, g_b is not defined
    

    Technical Explanation

    1. Using var

    In this case the reference g_a is created in what the ECMAScript spec calls "VariableEnvironment" that is attached to the current scope - this may be the a function execution context in the case of using var inside a function (though it may be get a little more complicated when you consider let) or in the case of "global" code the VariableEnvironment is attached to the global object (often window).

    References in the VariableEnvironment are not normally deletable - the process detailed in ECMAScript 10.5 explains this in detail, but suffice it to say that unless your code is executed in an eval context (which most browser-based development consoles use), then variables declared with var cannot be deleted.

    2. Without Using var

    When trying to assign a value to a name without using the var keyword, Javascript tries to locate the named reference in what the ECMAScript spec calls "LexicalEnvironment", and the main difference is that LexicalEnvironments are nested - that is a LexicalEnvironment has a parent (what the ECMAScript spec calls "outer environment reference") and when Javascript fails to locate the reference in a LexicalEnvironment, it looks in the parent LexicalEnvironment (as detailed in 10.3.1 and 10.2.2.1). The top level LexicalEnvironment is the "global environment", and that is bound to the global object in that its references are the global object's properties. So if you try to access a name that was not declared using a var keyword in the current scope or any outer scopes, Javascript will eventually fetch a property of the window object to serve as that reference. As we've learned before, properties on objects can be deleted.

    Notes

    1. It is important to remember that var declarations are "hoisted" - i.e. they are always considered to have happened in the beginning of the scope that they are in - though not the value initialization that may be done in a var statement - that is left where it is. So in the following code, a is a reference from the VariableEnvironment and not the window property and its value will be 10 at the end of the code:

      function test() { a = 5; var a = 10; }
      
    2. The above discussion is when "strict mode" is not enabled. Lookup rules are a bit different when using "strict mode" and lexical references that would have resolved to window properties without "strict mode" will raise "undeclared variable" errors under "strict mode". I didn't really understand where this is specified, but its how browsers behave.

    0 讨论(0)
  • 2020-11-22 05:08

    The delete operator removes a property from an object.

    delete object.property
    delete object['property']
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

    According to the question you need one of followings

    delete some_var;
    delete window.some_var;
    delete window['some_var'];
    
    0 讨论(0)
提交回复
热议问题