In javascript, how to specify read only properties while using Object.create()?
1 Answer
Using the Object.create() method you can specify the writable property in the descriptor, which lets you choose either to make the property writable or not (read-only), here it is:
var myObject = Object.create(Object.prototype, {
prop: {
value: 123,
writable: false
}
});
Now you can try to re-write your property and you'll see that it stays unchanged:
console.log(myObject.prop); // 123
myObject.prop = 0;
console.log(myObject.prop); // 123
For more information about the Object.create() method see the MDN documentation.
writable: false.