Search code examples
javascriptobjectwindowgetter

How to delete a window getter defined with Object.defineProperty


If I do this:

Object.defineProperty(window, 'hello',{ 
   get: ()=>"hello to you!"
});

which is invoked as:

hello

and replies with hello to you! How do I remove it?


Solution

  • You need to add another property to the descriptor object you passed in the defineProperty, which is configurable: true, after that you can delete the property buy using the delete operator.

    'use strict'
    Object.defineProperty(window, 'hello',{ 
      get: ()=>"hello to you!",
      configurable: true //make this true
    });
    console.log(window.hello);
    delete window.hello
    // hello is deleted from window
    console.log(window.hello);

    By default if you don't make the configurable as true for the descriptor object it is false, from the docs:

    configurable

    true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false.