On my attempt to learn more about Object.create I came across Object.create(): the New Way to Create Objects in JavaScript.
An example from the above page:
var Car2 = Object.create(null); //this is an empty object, like {}
Car2.prototype = {
getInfo: function() {
return 'A ' + this.color + ' ' + this.desc + '.';
}
};
var car2 = Object.create(Car2.prototype, {
//value properties
color: { writable: true, configurable:true, value: 'red' },
//concrete desc value
rawDesc: { writable: false, configurable:true, value: 'Porsche boxter' },
// data properties (assigned using getters and setters)
desc: {
configurable:true,
get: function () { return this.rawDesc.toUpperCase(); },
set: function (value) { this.rawDesc = value.toLowerCase(); }
}
});
car2.color = 'blue';
alert(car2.getInfo()); //displays 'A blue PORSCHE BOXTER.'
Question:
How correct is the above example?
This answer seems to contradict the example above.It seems to give the notion thatrawDesc
could be a private member that could be modified only via getter/setter ofdesc
. Is this useful in any way?Also, trying to set value for
desc
usingcar2.desc = 'Merc'
doesn't seem to work. Why is that so?What parts of Object.defineProperty and Object.create are similar?
Research:
Somewhat related question: Why can I set [enumerability and] writability of unconfigurable property descriptors?
I have tried removing writable: false
and value: 'Porsche boxter'
and tried setting the value but to no avail.