How to use JavaScript Object.defineProperty?

JavascriptObject Oriented ProgrammingFront End Technology

If you want to define a new or modify a property on an object, then use the Object.defineProperty in JavaScript. Use the property like the following −

Object.defineProperty(obj, prop, descriptor)

The following are the parameters −

  • obj – Property is defined on this object. 
  • prop – Name of the property 
  • descriptor  − The descriptor for the property

Example

You can try to run the following code to learn how to implement Object.defineProperty in JavaScript −

<!DOCTYPE html>
<html>
   <body>
      <script>
         const obj = {};

         Object.defineProperty(obj, 'prop', {
            value: 20,
            writable: false
         });
         obj.prop = 10;

         document.write(obj.prop);
      </script>
   </body>
</html>
raja
Updated on 23-Jun-2020 13:01:23

Advertisements