Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when do you use Object.defineProperty()

I'm wondering when I should use

Object.defineProperty 

to create new properties for an object. I'm aware that I'm able to set things like

enumerable: false 

but when do you need this really? If you just set a property like

myObject.myprop = 5; 

its descriptors are all set to true, right? I'm actually more curious when you guys use that rather verbose call to .defineProperty() and for what reasons.

like image 844
Andre Meinhold Avatar asked Apr 11 '12 12:04

Andre Meinhold


People also ask

What is the use of object defineProperty?

defineProperty() The static method Object. defineProperty() defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

What parameters does the function object defineProperty () accept?

Object. defineProperty allows you to set whether or not the property is enumerable, writable, and configurable as well as a value or a get/set (getter/setter) pair (see MDN Object.

What is the syntax of object defineProperty () method in JavaScript?

Syntax: Object. defineProperty(obj, prop, descriptor)

What is the difference between GET and defineProperty?

Using getter syntax you create a property which, prior to ES2015, you had to know the name of at the time that you were writing the code. Object. defineProperty allows you to perform the same as the above but, even before ES2015, does not require you to know the name of the property in advanced.


2 Answers

Object.defineProperty is mainly used to set properties with specific property descriptors (e.g. read-only (constants), enumerability (to not show a property in a for (.. in ..) loop, getters, setters).

"use strict"; var myObj = {}; // Create object // Set property (+descriptor) Object.defineProperty(myObj, 'myprop', {     value: 5,     writable: false }); console.log(myObj.myprop);// 5 myObj.myprop = 1;         // In strict mode: TypeError: myObj.myprop is read-only 

Example

This method extends the Object prototype with a property. Only the getter is defined, and the enumerability is set to false.

Object.defineProperty(Object.prototype, '__CLASS__', {     get: function() {         return Object.prototype.toString.call(this);     },     enumerable: false // = Default }); Object.keys({});           // [] console.log([].__CLASS__); // "[object Array]" 
like image 198
Rob W Avatar answered Oct 15 '22 09:10

Rob W


Features like 'enumerable' are rarely used in my experience. The major use case is computed properties:

var myObj = {};  myObj.width = 20; myObj.height = 20;  Object.defineProperty(myObj, 'area', {     get: function() {         return this.width*this.height;     } }); console.log(myObj.area); 
like image 23
Pascalius Avatar answered Oct 15 '22 08:10

Pascalius