How to unset a JavaScript variable?

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

    ECMAScript 2015 offers Reflect API. It is possible to delete object property with Reflect.deleteProperty():

    Reflect.deleteProperty(myObject, 'myProp');
    // it is equivalent to:
    delete myObject.myProp;
    delete myObject['myProp'];
    

    To delete property of global window object:

    Reflect.deleteProperty(window, 'some_var');
    

    In some cases properties cannot be deleted (when the property is not configurable) and then this function returns false (as well as delete operator). In other cases returns true:

    Object.defineProperty(window, 'some_var', {
        configurable: false,
        writable: true,
        enumerable: true,
        value: 'some_val'
    });
    
    var frozen = Object.freeze({ myProperty: 'myValue' });
    var regular = { myProperty: 'myValue' };
    var blank = {};
    
    console.log(Reflect.deleteProperty(window, 'some_var')); // false
    console.log(window.some_var); // some_var
    
    console.log(Reflect.deleteProperty(frozen, 'myProperty')); // false
    console.log(frozen.myProperty); // myValue
    
    console.log(Reflect.deleteProperty(regular, 'myProperty')); // true
    console.log(regular.myProperty); // undefined
    
    console.log(Reflect.deleteProperty(blank, 'notExistingProperty')); // true
    console.log(blank.notExistingProperty); // undefined
    

    There is a difference between deleteProperty function and delete operator when run in strict mode:

    'use strict'
    
    var frozen = Object.freeze({ myProperty: 'myValue' });
    
    Reflect.deleteProperty(frozen, 'myProperty'); // false
    delete frozen.myProperty;
    // TypeError: property "myProperty" is non-configurable and can't be deleted
    

提交回复
热议问题