Search code examples
javanashornwritable

Nashorn writable property


I am trying to use a non-writable property in an object literal in Nashorn in Java8 as follows:

'use strict';
var p =  { x: {value: 100, writable:false}};
p.x = 200; // should not allow to change x, but it does
print(p.x);

The code prints 200 where I am expecting an error because I have defined x as non-writable.

If I use the Object.defineProperty() function to create the property or set the property as non-writable, it works. The following code results in an error, as expected:

'use strict';
var p =  { x: {value: 100, writable:false}};
Object.defineProperty(p, "x", {writable:false});
p.x = 200; // An error
print(p.x);

My question is Why is setting the writable attribute to false in the expression { x: {value: 100, writable:false}} does not work in the first case? Is it a Nashorn bug or I am missing something?


Solution

  • it's not a Nashorn bug: you're just redefining the value of x (which was a hash) into something else.

    Nothing in javascript can stop this, unless you use Object.defineProperty as you did.