This question already has answers here:
Why are properties not shown when using Object.create() and console.log()?
(2 answers)
why console.log doesn't show values of properties added by PROTOTYPES in javascript when whole object is printed?
(2 answers)
Closed last year.
let animal = {
eats: true
};
let rabbit = Object.create(animal, {
jumps: {
value: true,
writable: true,
configurable: true
}
});
console.log(rabbit.__proto__); // logs: {eats: true};
console.log(animal); // logs: {eats: true};
console.log(rabbit.jumps); // logs: true;
console.log(rabbit); // logs {}
The question is: if rabbit is empty for real, what happend?
animal - has no jumps property
animal.proto - has no jumps property
rabbit - has no jumps property
rabbit.jumps - is true
Your new property is not enumerable - if it were it would show up in a text-based console (Your original code shows up in an object-based console like chrome for example):
const animal = {eats:true}
let rabbit = Object.create(animal, {
jumps: {
value: true,
writable: true,
configurable: true ,
enumerable:true
}
});
console.log(rabbit.__proto__); // logs: {eats: true};
console.log(animal); // logs: {eats: true};
console.log(rabbit.jumps); // logs: true;
console.log(rabbit); // logs as you expected
From the docs for Object.defineProperties():
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to 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)
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 made an object in my chrome extension and added a constant to it
const myObj = {};
Object.defineProperty(myObj , "DATABASES", { value: {}, writable: true, configurable: true });
Then I tried to add a value to that constant
myObj.DATABASES["key1"] = new Set(
{ a: "aaaa", b: "bbbb" }
);
The last line results in the following error, which doesn't make it clear to me which part of the statement is a problem:
Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
Can somebody tell me what's wrong with that last part?
Set expects an iterable object, like array, and you're passing it an object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#Syntax
I corrected the syntax with Clarity's link. It should be done as follows:
myObj.DATABASES["key1"] = new Set();
myObj.DATABASES["key1"].add({ a: "aaa", b: "bbbb" });
I have been following javascript design patterns and was implementing ES5 properties using the code found at this location.
https://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript
Test 1
Use a function to define 3 properties
Check the values are ok: SUCCESS
Log the object to see if the data looks ok: SUCCESS
Test 2
Use Object.definedProperties to define 3 properties
Check the values are ok: SUCCESS
Log the object to see if the data looks ok: FAIL
Test 1 Code
it('should construct object with some single properites added using helper function', function (done) {
var person = Object.create(Object.prototype);
// Populate the object with properties
pattern.defineProp(person, "car", "Delorean");
pattern.defineProp(person, "dateOfBirth", "1981");
pattern.defineProp(person, "hasBeard", false);
console.log(person.car);
console.log(person);
console.log(typeof person);
console.log(JSON.stringify(person));
person.car.should.equal('Delorean');
person.dateOfBirth.should.equal('1981');
person.hasBeard.should.equal(false);
// Produces
// Delorean
// { car: 'Delorean', dateOfBirth: '1981', hasBeard: false }
// object
// {"car":"Delorean","dateOfBirth":"1981","hasBeard":false}
done();
});
Test 2 Code
it('should construct object with multiple properties using standard ES5 syntax', function (done) {
var person = Object.create(Object.prototype);
// Populate the object with properties
Object.defineProperties(person, {
"car": {
value: "Delorean",
writable: true
},
"dateOfBirth": {
value: "1981",
writable: true
},
"hasBeard": {
value: false,
writable: true
}
});
console.log(person.car);
console.log(person);
console.log(typeof person);
console.log(JSON.stringify(person));
person.car.should.equal('Delorean');
person.dateOfBirth.should.equal('1981');
person.hasBeard.should.equal(false);
// Produces
// Delorean
// {}
// object
// {}
done();
});
Define Prop Function
exports.defineProp = function ( obj, key, value ){
var config = {
value: value,
writable: true,
enumerable: true,
configurable: true
};
Object.defineProperty( obj, key, config );
};
Well, if you are using the standard Object.defineProperties, and omit the enumerable attribute, it will default to false. Your properties won't be displayed because they are not enumerable.
I am trying to use javascript inheritance in my code. Following is the jsfiddle for the same.
http://jsfiddle.net/Fetsz/3/
var baseObject = Object.create(Object, {
// this works as an instance variable for derived objects
name: {
writable: true,
configurable: true,
enumerable: true,
value: null
},
// this should act as instance variable for derived objects
values: {
writable: true,
configurable: true,
enumerable: true,
value: []
},
displayAlert: {
value: function (){
alert("Alert from base object");
}
}
});
var derivedObj1 = Object.create(baseObject, {});
var derivedObj2 = Object.create(baseObject, {});
function displayValues (obj) {
alert("values for " + obj.name + "\n" + JSON.stringify(obj.values));
};
$(document).ready(function(){
derivedObj1.name = "Object 1";
derivedObj2.name = "Object 2";
derivedObj1.values.push("DO1 element");
derivedObj2.values.push("DO2 element");
derivedObj1.displayAlert();
// should display values added only for derivedObj1
displayValues(derivedObj1);
// should display values added only for derivedObj2
displayValues(derivedObj2);
});
I also checked following question which nicely explains why my code doesn't work. Javascript Inheritance: Parent's array variable retains value
I need to have an array member variable in every derived class which will contain certain values. I was trying to achieve the same by adding array in base class. As mentioned in above question, to achieve the same, I will have to add array member to each derived class. Is there any other way to achieve this without modifying every derived class?
When they are created, both derivedObj1.values and derivedObj2.values point to the same array object. If you were to first reassign each one using derivedObj1.values = [];, in the same way as you are reassigning the name property, your code would behave as expected.
Instead of adding the values property to the original baseObject, you could create an init method that adds an array to the instance:
var baseObject = Object.create(Object, {
// this works as an instance variable for derived objects
name: {
writable: true,
configurable: true,
enumerable: true,
value: null
},
// this should act as instance variable for derived objects
init: {
writable: true,
configurable: true,
enumerable: true,
value: function(){
this.values = [];
}
},
displayAlert: {
value: function (){
alert("Alert from base object");
}
}
});
var derivedObj1 = Object.create(baseObject, {});
derivedObj1.init();
var derivedObj2 = Object.create(baseObject, {});
derivedObj2.init();
Your variables can't be on the prototype if you don't want them to be shared by all instances. You could create a second object with just the property definition for the array,and pass it as the second parameter to Object.create:
var arrDef = {
values: {
writable: true,
configurable: true,
enumerable: true,
value: []
}
}
var derivedObj1 = Object.create(baseObject, arrDef);
var derivedObj2 = Object.create(baseObject, arrDef);