according to MDN, when using Object.defineProperty(), its third argument is a descriptor with some optional keys, such as
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.
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
Defaults to false.
...
I'd like to ask what does the defaults to false above mean?
I think it means that if I don't specify that key's value, it will be set to the default value, which is false, but when I try it in Chrome, it turns out to be as follows:
Object.getOwnPropertyDescriptor(o, 'a')
> {value: "c", writable: false, enumerable: true, configurable: true}
Object.defineProperty(o, 'a', {'enumerable': false})
> {a: "c"}
Object.getOwnPropertyDescriptor(o, 'a')
> {value: "c", writable: false, enumerable: false, configurable: true}
Apparently my descriptor missed the key configurable, but this attribute was not set to false.
Thanks for your help!
Quoting the same MDN article:
When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration.
Since o.a already exists, Object.defineProperty() modifies the property with provided descriptor instead of defining it from scratch. In this case it only overwrites the keys you provide.
You can see the defaults in action by defining a new property.
var o = {}
> undefined
Object.defineProperty(o, 'a', {})
> {a: undefined}
Object.getOwnPropertyDescriptor(o, 'a')
> {value: undefined, writable: false, enumerable: false, configurable: false}
Related
I was playing with below javascript code. Understanding of Object.defineProperty() and I am facing a strange issue with it. When I try to execute below code in the browser or in the VS code the output is not as expected whereas if I try to debug the code the output is correct
When I debug the code and evaluate the profile I can see the name & age property in the object
But at the time of output, it only shows the name property
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true
})
console.log(profile)
console.log(profile.age)
Now expected output here should be
{name: "Barry Allen", age: 23}
23
but I get the output as.
Note that I am able to access the age property defined afterwards.
I am not sure why the console.log() is behaving this way.
{name: "Barry Allen"}
23
You should set enumerable to true. In Object.defineProperty its false by default. According to MDN.
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
Defaults to false.
Non-enumerable means that property will not be shown in Object.keys() or for..in loop neither in console
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
All the properties and methods on prototype object of built-in classes are non-enumerable. Thats is the reason you can call them from instance but they don't appear while iterating.
To get all properties(including non-enumerable)Object.getOwnPropertyNames()
.
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: false
})
for(let key in profile) console.log(key) //only name will be displayed.
console.log(Object.getOwnPropertyNames(profile)) //You will se age too
By default, properties you define with defineProperty are not enumerable - this means that they will not show up when you iterate over their Object.keys (which is what the snippet console does). (Similarly, the length property of an array does not get displayed, because it's non-enumerable.)
See MDN:
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
Defaults to false.
Make it enumerable instead:
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
The reason you can see the property in the logged image is that Chrome's console will show you non-enumerable properties as well - but the non-enumerable properties will be slightly greyed-out:
See how age is grey-ish, while name is not - this indicates that name is enumerable, and age is not.
Whenever you use".defineProperty" method of object. You should better define all the properties of the descriptor. Because if you don't define other property descriptor then it assumes default values for all of them which is false. So your console.log checks for all the enumerable : true properties and logs them.
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable : true,
configurable : true
})
console.log(profile)
console.log(profile.age)
In the documentation of the Proxy ownKeys trap on MDN it states that it will intercept Object.keys() calls:
This trap can intercept these operations:
Object.getOwnPropertyNames()
Object.getOwnPropertySymbols()
Object.keys()
Reflect.ownKeys()
However, from my tests it doesn't seem to work with Object.keys:
const proxy = new Proxy({}, {
ownKeys() {
console.log("called")
return ["a", "b", "c"]
}
})
console.log(Object.keys(proxy))
console.log(Object.getOwnPropertyNames(proxy))
console.log(Reflect.ownKeys(proxy))
Is MDN wrong, or am I doing something wrong?
The reason is simple: Object.keys returns only properties with the enumerable flag. To check for it, it calls the internal method [[GetOwnProperty]] for every property to get its descriptor. And here, as there’s no property, its descriptor is empty, no enumerable flag, so it’s skipped.
For Object.keys to return a property, we need it to either exist in the object, with the enumerable flag, or we can intercept calls to [[GetOwnProperty]] (the trap getOwnPropertyDescriptor does it), and return a descriptor with enumerable: true.
Here’s an example of that:
let user = { };
user = new Proxy(user, {
ownKeys(target) { // called once to get a list of properties
return ['a', 'b', 'c'];
},
getOwnPropertyDescriptor(target, prop) { // called for every property
return {
enumerable: true,
configurable: true
/* ...other flags, probable "value:..." */
};
}
});
console.log( Object.keys(user) ); // ['a', 'b', 'c']
Source
Object.keys returns only the enumerable own properties of an object. Your proxy doesn't have such, or at least it doesn't report them in its getOwnPropertyDescriptor trap. It works with
const proxy = new Proxy({}, {
ownKeys() {
console.log("called ownKeys")
return ["a", "b", "c"]
},
getOwnPropertyDescriptor(target, prop) {
console.log(`called getOwnPropertyDescriptor(${prop})`);
return { configurable: true, enumerable: true };
}
})
console.log(Object.keys(proxy))
console.log(Object.getOwnPropertyNames(proxy))
console.log(Reflect.ownKeys(proxy))
When I first encountered the basics of JavaScript, the most curious thing was why 'length' and 'proto' works different from any other properties.
I could get a clue when I heard that there were 'getters' and 'setters' in JS.
However, I am asking this question becaues I still have questions after I study more.
[1] for 'proto'
let obj = {}
obj.hasOwnProperty('__proto__') // false
Object.getOwnPropertyDescriptor(Object.prototype, '__proto__')
/*
{
configurable: true,
enumerable: false,
get: [[some function]],
set: [[some function]]
}
*/
I've found that 'proto' is an accessor property in Object.prototype, not a data property in obj.
[2] for 'length'
let arr = [1, 2]
Object.getOwnPropertyDescriptor(arr, 'length')
/*
{
value: 2,
writable: true,
enumerable: false,
configurable: false
}
*/
Object.getOwnPropertyDescriptor(Array.prototype, 'length')
/*
{
value: 0,
writable: true,
enumerable: false,
configurable: false
}
*/
The case of 'length' is different.
It's data property of arr. (Array.prototype also have one)
I'm curious how length properties are renewed whenever arrays change, or they remove/add elements (even if it is undefined) whenever 'length' changes.
Is it just the grammatical action of JavaScript??
I could say this differently.
Can I assign properties which act like 'length' to my own objects??
I apologize in advance if this has been asked elsewhere or if I have missed something important in the docs, well, but I need to ask this:
Let's say an object is being created without defining the respective properties
cons objA = Object.create({
init(text) {
this.text = text;
}
});
or an object is being created and the respective property has been declared in the properties object
const objB = Object.create({
init(text) {
this.text = text;
}
}, {
text: {
value: '',
writable: true
}
});
I understand that defining properties in the propertiesObject of Object.create helps defining and providing better contracts,
but
do these two scenarios vary in respect to the text property?
Yes, they vary - there is difference between a and b results
const a = Object.create({
init(text) {
this.text = text;
}
});
const b = Object.create({
init(text) {
this.text = text;
}
}, {
text: {
value: '',
writable: true
}
});
console.log(Object.getOwnPropertyNames(a))
console.log(Object.getOwnPropertyNames(b))
a.init('a text');
b.init('b text');
console.log(Object.getOwnPropertyDescriptor(a, 'text'))
console.log(Object.getOwnPropertyDescriptor(b, 'text'))
a returns:
{
"value": "a text",
"writable": true,
"enumerable": true,
"configurable": true
}
b returns:
{
"value": "b text",
"writable": true,
"enumerable": false,
"configurable": false
}
By default property is enumerable and configurable unless you define property by Object.defineProperty or Object.create. You can define them as you did with writable.
Enumerable works in certain object-property enumerations, such as the for..in.
Configurable means that you cannot use Object.defineProperty again on this property (there will be Cannot redefine property: text error).
Other than that - before you use init() - a object will have undefined text property (that is not enumerable, not configurable, writable) and object b will not have any property.
What is the problem?
var yie = Object.create({}, {
'currentDoAction': {
value: null,
enumerable: true,
writeable: true
},
'success': {
value: function(result) {
this.currentDoAction = "should be changed";
console.log(this.currentDoAction); // prints out null ... why ?
},
enumerable: true,
writeable: true,
}
});
see the comment in the success function where this.currentDoAction still appears to be null even though it should be changed in the line before.
The problem is that you've misspelled writable (nb: no "e"), so that property key is ignored and the default value of writable: false is used instead.
See http://jsfiddle.net/szLju/ for a working version.
One problem I can see is that you have a trailing comma and some browsers don't like this:
writeable: true,
^