How to unset a JavaScript variable?

后端 未结 11 2043
执笔经年
执笔经年 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:45

    @scunlife's answer will work, but technically it ought to be

    delete window.some_var; 
    

    delete is supposed to be a no-op when the target isn't an object property. e.g.,

    (function() {
       var foo = 123;
       delete foo; // wont do anything, foo is still 123
       var bar = { foo: 123 };
       delete bar.foo; // foo is gone
    }());
    

    But since global variables are actually members of the window object, it works.

    When prototype chains are involved, using delete gets more complex because it only removes the property from the target object, and not the prototype. e.g.,

    function Foo() {}
    Foo.prototype = { bar: 123 };
    var foo = new Foo();
    // foo.bar is 123
    foo.bar = 456;
    // foo.bar is now 456
    delete foo.bar;
    // foo.bar is 123 again.
    

    So be careful.

    EDIT: My answer is somewhat inaccurate (see "Misconceptions" at the end). The link explains all the gory details, but the summary is that there can be big differences between browsers and depending on the object you are deleting from. delete object.someProp should generally be safe as long as object !== window. I still wouldn't use it to delete variables declared with var although you can under the right circumstances.

提交回复
热议问题