Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I redefine a property in a Javascript object?

Tags:

javascript

I am creating a object using Object.create and I want to add properties to it.

> var o = Object.create({}); undefined  > Object.defineProperty(o, "foo", {value: 43, enumerable: true}); {foo: 43}  > o {foo: 43}  > o.foo 43  > for (var i in o) { console.log(i); } foo  > Object.keys(o) ['foo']  > Object.defineProperty(o, "foo", {value: 43, enumerable: false }); TypeError: Cannot redefine property: bar 

Q1) Why can't I redefine the property ?

> o.__proto__ {}  > o.prototype undefined 

Q2) Why is the prototype empty ? And why are these 2 values different i.e. {} vs undefined ?

like image 850
Gavin Bong Avatar asked Aug 27 '14 02:08

Gavin Bong


People also ask

Can we define an object in Javascript which property can not be changed?

the type of this property cannot be changed between data property and accessor property, and. the property may not be deleted, and. other attributes of its descriptor cannot be changed (however, if it's a data descriptor with writable: true , the value can be changed, and writable can be changed to false ).

What is the syntax of object define property method in Javascript?

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


1 Answers

You are unable to redefine the property because Object.defineProperty() defaults to non-configurable properties, 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.

So this defaults to false - you'd need to pass it configurable: true to allow it.

like image 70
jdphenix Avatar answered Sep 29 '22 12:09

jdphenix