I have the following function based on Node-Express:
//function on server side
app.get('/loginCheck', loggedCheck, function(req, res) {
var data = {local: {}, facebook: {}};
data.id = req.user._id;
data.local.email = req.user.local.email;
data.local.fname = req.user.local.fname;
data.local.lname = req.user.local.lname ;
data.local.college = req.user.local.college ;
data.local.degree = req.user.local.degree ;
data.year = req.user.year ;
data.mobile = req.user.mobile ;
data.city = req.user.city ;
data.facebook.id = req.user.facebook.id ;
//res.json(data);
var x = {};
x.name = "someName"
res.json(x);
})
Following is the code on client side which makes an ajax requests:
//function on client side making an ajax request
$.get("/loginCheck",function(data,status){
console.log(data);
});
In the former code on server side, req.user is a mongodb object created by mongoose. What I want to do is send the data object (which has some selected attributes of req.user object) and send the object as JSON as response.
The variable x is a custom created variable.
The problem is:
When I send the data object to client, __proto__ attribute is also added with the object which is not happening when I am sending x to the client.
But, I don't want the __proto__ in the client side, because, from some articles, I found that there are security issues with __proto__.
I need help on how to remove __proto__ from the data object.
You can forego a prototype on an object simply by using Object.create(null) and defining the properties you wish to use.
var obj = Object.create(null);
Object.defineProperty(obj, {
'foo': {
value: 1,
enumerable: true,
},
'bar': {
value: 2,
enumerable: false
}
});
// or...
obj.foo = 1
obj.bar = 2
/* various checks */
obj instanceof Object; // false
Object.prototype.isPrototypeOf(obj); // false
Object.getPrototypeOf(obj); // null
obj + ""; // TypeError: Cannot convert object to primitive value
'toString' in obj; // false
foo; // 1
obj['bar']; // 2
JSON.stringify(obj); // {"foo":1}
{}.hasOwnProperty.call(obj, 'foo'); // true
{}.propertyIsEnumerable.call(obj, 'bar'); // false
And in this approach, you no longer need to check for obj.hasOwnProperty(key)
for (var key in obj) {
// do something
}
Read More: True Hash Maps in JavaScript
MDN:
Object.defineProperty() &
Object.create()
// with __proto__
var obj = {} // equivalent to Object.create(Object.prototype);
obj.key = 'value'
console.log(obj)
// without __proto__
var bareObj = Object.create(null)
Object.defineProperty(bareObj, {
'key': {
value: 'value',
enumerable: false,
configurable: true,
writable: true
}
})
// or... bareObj.key = 'value'
console.log(bareObj)
You don't need to remove that. It doesn't cause any trouble/problem.
You can use like this.
$.each(data, function(k, v) {
console.log(k, v);
});
Sending __proto__ out from the server can create a JSON object that may break things if the keys are transferred to another object without removing __proto__ or leak sensitive data.
It's unusual that it would appear in encoded JSON as it is usually ignored. That suggests there might be a problem or kludge elsewhere. It's possible the library you're using it leaking it by accident or making use of it. It may be alright to make use of it in a closed system but it should not be allowed either into or out of the system.
// If is optional.
if('__proto__' in obj)
// This may cause unintended consequences.
delete(obj.__proto__);
On receiving data you should also be very careful that it doesn't contain a __proto__ property. This can crash or compromise the server if that key is copied over to another object.
If creating your own object there are tricks to change it's behaviour such as using defineProperty but these tricks tend not to eliminate the problem entirely.
Just write
String(<put here your data>)
Related
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.
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]"
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);
A really good reason for using Object.defineProperty is that it lets you loop through a function in an object as a computed property, which executes the function instead of returning the function's body.
For example:
var myObj = {};
myObj.width = 20;
myObj.height = 20;
Object.defineProperty(myObj, 'area', {
get: function() {
return this.width*this.height;
},
enumerable: true
});
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
console.log(key + " -> " + myObj[key]);
}
}
//width -> 20, height -> 20, area -> 400
Versus adding the function as a property to an object literal:
var myObj = {};
myObj.width = 20;
myObj.height = 20;
myObj.area = function() {
return this.width*this.height;
};
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
console.log(key + " -> " + myObj[key]);
}
}
// width -> 20, height -> 20, area -> function() { return this.width*this.height;}
Make sure you set the enumerable property to true in order to loop through it.
For example, that's how Vue.js keeps track of changes in the data object:
When you pass a plain JavaScript object to a Vue instance as its data option, Vue will walk through all of its properties and convert them to getter/setters using Object.defineProperty. This is an ES5-only and un-shimmable feature, which is why Vue doesn’t support IE8 and below.
The getter/setters are invisible to the user, but under the hood they enable Vue to perform dependency-tracking and change-notification when properties are accessed or modified.
[...]
Keep in mind that even a super slim and basic version of Vue.js would use something more than just Object.defineProperty, but the main functionality comes from it:
Here you can see an article where the author implements a minimal PoC version of something like Vue.js: https://medium.com/js-dojo/understand-vue-reactivity-implementation-step-by-step-599c3d51cd6c
And here a talk (in Spanish) where the speaker builds something similar while explaining reactivity in Vue.js: https://www.youtube.com/watch?v=axXwWU-L7RM
Summary:
In Javascript Objects are collections of key-value pairs.
Object.defineProperty() is a function which can define a new property on an object and can set the following attributes of a property:
value <any>: The value associated with the key
writable <boolean>: if writable is set to true The property can be updated by assigning a new value to it. If set to false you can't change the value.
enumerable <boolean>: if enumerable is set to true Property can be accessed via a for..in loop. Furthermore are the only the enumerable property keys returned with Object.keys()
configurable <boolean>: If configurable is set to false you cannot change change the property attributes (value/writable/enumerable/configurable), also since you cannot change the value you cannot delete it using the delete operator.
Example:
let obj = {};
Object.defineProperty(obj, 'prop1', {
value: 1,
writable: false,
enumerable: false,
configurable: false
}); // create a new property (key=prop1, value=1)
Object.defineProperty(obj, 'prop2', {
value: 2,
writable: true,
enumerable: true,
configurable: true
}); // create a new property (key=prop2, value=2)
console.log(obj.prop1, obj.prop2); // both props exists
for(const props in obj) {
console.log(props);
// only logs prop2 because writable is true in prop2 and false in prop1
}
obj.prop1 = 100;
obj.prop2 = 100;
console.log(obj.prop1, obj.prop2);
// only prop2 is changed because prop2 is writable, prop1 is not
delete obj.prop1;
delete obj.prop2;
console.log(obj.prop1, obj.prop2);
// only prop2 is deleted because prop2 is configurable and prop1 is not
Object.defineProperty prevents you from accidentally assigning values to some key in its prototype chain. With this method you assign only to that particular object level(not to any key in prototype chain).
For example:
There is an object like {key1: value1, key2: value2} and you don't know exactly its prototype chain or by mistake you miss it and there is some property 'color' somewhere in prototype chain then-
using dot(.) assignment-
this operation will assign value to key 'color' in prototype chain(if key exist somewhere) and you will find the object with no change as .
obj.color= 'blue'; // obj remain same as {key1: value1, key2: value2}
using Object.defineProperty method-
Object.defineProperty(obj, 'color', {
value: 'blue'
});
// now obj looks like {key1: value1, key2: value2, color: 'blue'}. it adds property to the same level.Then you can iterate safely with method Object.hasOwnProperty().
One neat use case I have seen for defineProperty is for libraries to provide an error property to the user which, if it's not accessed within a certain interval you would log the error yourself. For example:
let logErrorTimeoutId = setTimeout(() => {
if (error) {
console.error('Unhandled (in <your library>)', error.stack || error);
}
}, 10);
Object.defineProperty(data, 'error', {
configurable: true,
enumerable: true,
get: () => {
clearTimeout(logErrorTimeoutId);
return error;
},
});
Source for this code: https://github.com/apollographql/react-apollo/blob/ddd3d8faabf135dca691d20ce8ab0bc24ccc414e/src/graphql.tsx#L510
A good use is when you need to do some interception or apply a classical Observer/Observable pattern in a elegant way:
https://www.monterail.com/blog/2016/how-to-build-a-reactive-engine-in-javascript-part-1-observable-objects
A very useful case is to monitor changes to something and act on them. It's easy because you can have callback functions fire whenever the value gets set. Here's a basic example.
You have an object Player that can be playing or not playing. You want something to happen right when it starts playing, and right when it stops playing.
function Player(){}
Object.defineProperty(Player.prototype, 'is_playing', {
get(){
return this.stored_is_playing; // note: this.is_playing would result in an endless loop
},
set(newVal){
this.stored_is_playing = newVal;
if (newVal === true) {
showPauseButton();
} else {
showPlayButton();
}
}
});
const cdplayer = new Player();
cdplayer.is_playing = true; // showPauseButton fires
This answer is related to a couple other answers here, which are good stepping points for more information, but with no need to follow external links to read about libraries or programming paradigms.
#Gerard Simpson
If 'area' should be enumerable it can be written without Object.defineProperty, too.
var myObj = {
get area() { return this.width * this.height }
};
myObj.width = 20;
myObj.height = 20;
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
console.log(key + " -> " + myObj[key]);
}
}
//area -> 400, width -> 20, height -> 20
Background to this question
I recently started to get into test-driven development (TDD) in Javascript using karma and Jasmine. I would like to develop proper tests along with good code that takes care of all eventualities. This also means for me to check for the right types of objects inside my test cases.
Current problem
JSON Data returned from an AJAX call should be matched against an object to make sure the right data is returned. To do so I came up with the following code (simplified);
var MyClass = {};
Object.defineProperties(MyClass, {
Key: {
value: '',
writable: true
}
});
var sealed = Object.seal(MyClass);
try {
$.extend(sealed, jsonResponse);
return sealed;
} catch(e) {
return false;
}
This works as expected and in case any extra properties are part of the JSON false will be returned. So far, so good. What I would like to also do is to check if the returned data is of the right "type". I could do so by using a function instead of an object:
var MyClass = function() {
this.key= '123';
};
var myClass = new MyClass();
console.log(myClass instanceof MyClass); // True
But I can't come up with an idea how to combine both so I can both make sure that no attributes are added to the object and also to be able to check for the right "Class". In the first case typeof sealed would always yield "object".
Restrictions
I need to also support Internet Explorer 11 so I can't use class MyClass { ... }.
If I'm understanding you correctly, the combined version would be:
// The "class"
var MyClass = function(data) {
// Create all the allowed properties
this.key = '123';
// Seal the instance so others can't be created
Object.seal(this);
// If data was supplied, apply it
if (data) {
$.extend(this, data);
}
};
// The instance that you'd use, note passing in the parsed JSON daa
var myClass = new MyClass(jsonResponse);
console.log(myClass instanceof MyClass); // true
Live Example:
// The "class"
var MyClass = function(data) {
// Create all the allowed properties
this.key = '123';
// Seal the instance so others can't be created
Object.seal(this);
// If data was supplied, apply it
if (data) {
$.extend(this, data);
}
};
var jsonResponse = {
key: "456"
};
// The instance that you'd use, note passing in the parsed JSON daa
var myClass = new MyClass(jsonResponse);
console.log(myClass instanceof MyClass); // true
console.log(myClass.key); // "456"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
That will throw an error if jsonResponse contains properties that MyClass doesn't allow, because trying to create a new property on a sealed object throws an error. You've said in the comments that's what you want (which makes sense).
If it weren't what you want, you could write your own function to copy the properties rather than using $.extend:
function applyData(obj, data) {
var own = Object.prototype.hasOwnProperty.bind(obj);
Object.keys(data).filter(own).forEach(function(key) {
obj[key] = data[key];
});
}
(Or use an in check if you want to allow inherited properties — for instance, accessor properties — to be set.)
(You could just use an if in the forEach callback rather than .filter(own).)
Then use that function instead of $.extend.
Live Example:
// The function to apply the data
function applyData(obj, data) {
var own = Object.prototype.hasOwnProperty.bind(obj);
Object.keys(data).filter(own).forEach(function(key) {
obj[key] = data[key];
});
}
// The "class"
var MyClass = function(data) {
// Create all the allowed properties
this.key = '123';
// Seal the instance so others can't be created
Object.seal(this);
// If data was supplied, apply it
if (data) {
applyData(this, data);
}
};
var jsonResponse = {
key: "456",
extra: "will be ignored"
};
// The instance that you'd use, note passing in the parsed JSON daa
var myClass = new MyClass(jsonResponse);
console.log(myClass instanceof MyClass); // true
console.log(myClass.key); // "456"
console.log(myClass.extra); // undefined
But your approach of having an error makes sense.
I want to create a closed object in javascript, that can be edited only using Object.defineProperty and not to be edited it in the normal way...
The goal is, I am creating a lib, where users can read an object called dictionary, but they can edit it too! is there any way to have an object that can be read by users, and edited by me ?
It is just not possible to protect any object parts.
See also:
How to Create Protected Object Properties in JavaScript
You can provide some basic protection using Object.defineProperty like this:
var o = { a: 5 };
o._protected = {};
o._protected.a = o.a;
Object.defineProperty(o, 'a', {
get: function() { return this._protected.a; },
set: function(value) {
if (value > 0 && value < 5) {
this._protected.a = value;
}
configurable: false
});
This will constrain changes to property a in this object so they will go through the get (read) / set (update). Of course, in this case the _protected object can be manipulated but it does require the user to consciously 'hack' it. Attempts to directly change property a would be under your control.
In this example, an attempt to set o.a = 6 would result in no change to o.a (of course, you could set it to the maximum allowed value in your set function if that were preferable).
You can prevent changes to o.a by not providing a set function.
This can be handy for ensuring properties only get 'valid' values and I've often used it that way.
I found it! please tell me what's the wrong with this solution:
var protected = {}
Object.defineProperty(this,
'setter', {
value: function(name , value) {
protected[name] = value
},
writable: false,
})
Object.defineProperty(this,
'getter', {
value: function(name , value) {
return JSON.parse(JSON.stringify(protected))
},
writable: false,
})
Object.freeze(this.setter)
Object.freeze(this.getter)
I would like to add key-value pairs of metadata to arbitrary JavaScript objects. This metadata should not affect code that is not aware of the metadata, that means for example
JSON.stringify(obj) === JSON.stringify(obj.WithMetaData('key', 'value'))
MetaData aware code should be able to retrieve the data by key, i.e.
obj.WithMetaData('key', 'value').GetMetaData('key') === 'value'
Is there any way to do it - in node.js? If so, does it work with builtin types such as String and even Number? (Edit Thinking about it, I don't care about real primitives like numbers, but having that for string instances would be nice).
Some Background: What I'm trying to do is cache values that are derived from an object with the object itself, so that
to meta data unaware code, the meta data enriched object will look the same as the original object w/o meta
code that needs the derived values can get it out of the meta-data if already cached
the cache will get garbage collected alongside the object
Another way would be to store a hash table with the caches somewhere, but you'd never know when the object gets garbage collected. Every object instance would have to be taken care of manually, so that the caches don't leak.
(btw clojure has this feature: http://clojure.org/metadata)
You can use ECMA5's new object properties API to store properties on objects that will not show up in enumeration but are nonetheless retrievable.
var myObj = {};
myObj.real_property = 'hello';
Object.defineProperty(myObj, 'meta_property', {value: 'some meta value'});
for (var i in myObj)
alert(i+' = '+myObj[i]); //only one property - #real_property
alert(myObj.meta_property); //"some meta value"
More information here: link
However you're not going to be able to do this on primitive types such as strings or numbers, only on complex types.
[EDIT]
Another approach might be to utilise a data type's prototype to store meta. (Warning, hack ahead). So for strings:
String.prototype.meta = {};
String.prototype.addMeta = function(name, val) { this.meta[name] = val; }
String.prototype.getMeta = function(name) { return this.meta[name]; };
var str = 'some string value';
str.addMeta('meta', 'val');
alert(str.getMeta('meta'));
However this is clearly not ideal. For one thing, if the string was collected or aliased (since simple data types are copied by value, not reference) you would lose this meta. Only the first approach has any mileage in a real-world environment, to be honest.
ES6 spec introduces Map and WeakMap. You can enable these in node by running node --harmony and by enabling the experimental javascript flag in Chrome, (it's also in Firefox by default). Maps and WeakMaps allow objects to be used as keys which can be be used to store metadata about objects that isn't visible to anyone without access to the specific map/weakmap. This is a pattern I now use a lot:
function createStorage(creator){
creator = creator || Object.create.bind(null, null, {});
var map = new Map;
return function storage(o, v){
if (1 in arguments) {
map.set(o, v);
} else {
v = map.get(o);
if (v == null) {
v = creator(o);
map.set(o, v);
}
}
return v;
};
}
Use is simple and powerful:
var _ = createStorage();
_(someObject).meta= 'secret';
_(5).meta = [5];
var five = new Number(5);
_(five).meta = 'five';
console.log(_(someObject).name);
console.log(_(5).meta);
console.log(_(five).meta);
It also facilitates some interesting uses for separating implementation from interface:
var _ = createStorage(function(o){ return new Backing(o) });
function Backing(o){
this.facade = o;
}
Backing.prototype.doesStuff = function(){
return 'real value';
}
function Facade(){
_(this);
}
Facade.prototype.doSomething = function doSomething(){
return _(this).doesStuff();
}
There is no "comment" system in JSON. The best you can hope for is to add a property with an unlikely name, and add that key contaning the metadata. You can then read the metadata back out if you know it's metadata, but other setups will just see it as another property. And if someone uses for..in...
You could just add the Metadata as a "private" variable!?
var Obj = function (meta) {
var meta = meta;
this.getMetaData = function (key) {
//do something with the meta object
return meta;
};
};
var ins_ob = new Obj({meta:'meta'});
var ins_ob2 = new Obj();
if(JSON.stringify(ins_ob) === JSON.stringify(ins_ob2)) {
console.log('hoorai');
};
If you want object-level metadata, you could create a class that extends Object. Getters and setters are not enumerable and, obviously, neither are private fields.
class MetadataObject extends Object {
#metadata = undefined;
get metadata() { return this.#metadata; }
set metadata(value) { this.#metadata; }
}
var obj = new MetadataObject();
obj.a = 1;
obj.b = 2;
obj.metadata = { test: 123 };
console.log(obj); // { a: 1, b: 2 }
console.log(obj.metadata); // { test: 123 }
console.log(JSON.stringify(obj)); // '{"a":1,"b":2}'
You can even simplify the implementation using a Map. Without a setter on metadata, you have to use Map methods to modify it.
class MetadataObject extends Object {
#metadata = new Map();
get metadata() { return this.#metadata; }
}
var obj = new MetadataObject();
obj.a = 1;
obj.b = 2;
obj.metadata.set('test', 123);
console.log(obj); // { a: 1, b: 2 }
console.log(obj.metadata.get('test')); // 123
console.log(JSON.stringify(obj)); // '{"a":1,"b":2}'
I ran into a situation where I needed property level metadata, and used the latter implementation.
obj.id = 1;
obj.metadata.set('id', 'metadata for the id property');
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.
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]"
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);
A really good reason for using Object.defineProperty is that it lets you loop through a function in an object as a computed property, which executes the function instead of returning the function's body.
For example:
var myObj = {};
myObj.width = 20;
myObj.height = 20;
Object.defineProperty(myObj, 'area', {
get: function() {
return this.width*this.height;
},
enumerable: true
});
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
console.log(key + " -> " + myObj[key]);
}
}
//width -> 20, height -> 20, area -> 400
Versus adding the function as a property to an object literal:
var myObj = {};
myObj.width = 20;
myObj.height = 20;
myObj.area = function() {
return this.width*this.height;
};
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
console.log(key + " -> " + myObj[key]);
}
}
// width -> 20, height -> 20, area -> function() { return this.width*this.height;}
Make sure you set the enumerable property to true in order to loop through it.
For example, that's how Vue.js keeps track of changes in the data object:
When you pass a plain JavaScript object to a Vue instance as its data option, Vue will walk through all of its properties and convert them to getter/setters using Object.defineProperty. This is an ES5-only and un-shimmable feature, which is why Vue doesn’t support IE8 and below.
The getter/setters are invisible to the user, but under the hood they enable Vue to perform dependency-tracking and change-notification when properties are accessed or modified.
[...]
Keep in mind that even a super slim and basic version of Vue.js would use something more than just Object.defineProperty, but the main functionality comes from it:
Here you can see an article where the author implements a minimal PoC version of something like Vue.js: https://medium.com/js-dojo/understand-vue-reactivity-implementation-step-by-step-599c3d51cd6c
And here a talk (in Spanish) where the speaker builds something similar while explaining reactivity in Vue.js: https://www.youtube.com/watch?v=axXwWU-L7RM
Summary:
In Javascript Objects are collections of key-value pairs.
Object.defineProperty() is a function which can define a new property on an object and can set the following attributes of a property:
value <any>: The value associated with the key
writable <boolean>: if writable is set to true The property can be updated by assigning a new value to it. If set to false you can't change the value.
enumerable <boolean>: if enumerable is set to true Property can be accessed via a for..in loop. Furthermore are the only the enumerable property keys returned with Object.keys()
configurable <boolean>: If configurable is set to false you cannot change change the property attributes (value/writable/enumerable/configurable), also since you cannot change the value you cannot delete it using the delete operator.
Example:
let obj = {};
Object.defineProperty(obj, 'prop1', {
value: 1,
writable: false,
enumerable: false,
configurable: false
}); // create a new property (key=prop1, value=1)
Object.defineProperty(obj, 'prop2', {
value: 2,
writable: true,
enumerable: true,
configurable: true
}); // create a new property (key=prop2, value=2)
console.log(obj.prop1, obj.prop2); // both props exists
for(const props in obj) {
console.log(props);
// only logs prop2 because writable is true in prop2 and false in prop1
}
obj.prop1 = 100;
obj.prop2 = 100;
console.log(obj.prop1, obj.prop2);
// only prop2 is changed because prop2 is writable, prop1 is not
delete obj.prop1;
delete obj.prop2;
console.log(obj.prop1, obj.prop2);
// only prop2 is deleted because prop2 is configurable and prop1 is not
Object.defineProperty prevents you from accidentally assigning values to some key in its prototype chain. With this method you assign only to that particular object level(not to any key in prototype chain).
For example:
There is an object like {key1: value1, key2: value2} and you don't know exactly its prototype chain or by mistake you miss it and there is some property 'color' somewhere in prototype chain then-
using dot(.) assignment-
this operation will assign value to key 'color' in prototype chain(if key exist somewhere) and you will find the object with no change as .
obj.color= 'blue'; // obj remain same as {key1: value1, key2: value2}
using Object.defineProperty method-
Object.defineProperty(obj, 'color', {
value: 'blue'
});
// now obj looks like {key1: value1, key2: value2, color: 'blue'}. it adds property to the same level.Then you can iterate safely with method Object.hasOwnProperty().
One neat use case I have seen for defineProperty is for libraries to provide an error property to the user which, if it's not accessed within a certain interval you would log the error yourself. For example:
let logErrorTimeoutId = setTimeout(() => {
if (error) {
console.error('Unhandled (in <your library>)', error.stack || error);
}
}, 10);
Object.defineProperty(data, 'error', {
configurable: true,
enumerable: true,
get: () => {
clearTimeout(logErrorTimeoutId);
return error;
},
});
Source for this code: https://github.com/apollographql/react-apollo/blob/ddd3d8faabf135dca691d20ce8ab0bc24ccc414e/src/graphql.tsx#L510
A good use is when you need to do some interception or apply a classical Observer/Observable pattern in a elegant way:
https://www.monterail.com/blog/2016/how-to-build-a-reactive-engine-in-javascript-part-1-observable-objects
A very useful case is to monitor changes to something and act on them. It's easy because you can have callback functions fire whenever the value gets set. Here's a basic example.
You have an object Player that can be playing or not playing. You want something to happen right when it starts playing, and right when it stops playing.
function Player(){}
Object.defineProperty(Player.prototype, 'is_playing', {
get(){
return this.stored_is_playing; // note: this.is_playing would result in an endless loop
},
set(newVal){
this.stored_is_playing = newVal;
if (newVal === true) {
showPauseButton();
} else {
showPlayButton();
}
}
});
const cdplayer = new Player();
cdplayer.is_playing = true; // showPauseButton fires
This answer is related to a couple other answers here, which are good stepping points for more information, but with no need to follow external links to read about libraries or programming paradigms.
#Gerard Simpson
If 'area' should be enumerable it can be written without Object.defineProperty, too.
var myObj = {
get area() { return this.width * this.height }
};
myObj.width = 20;
myObj.height = 20;
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
console.log(key + " -> " + myObj[key]);
}
}
//area -> 400, width -> 20, height -> 20