How to prevent built-in functions or objects to be overwritten?
Sundararajan Athijegannathan
sundararajan.athijegannathan at oracle.com
Tue Mar 1 03:03:09 UTC 2016
You can use Object.defineProperty function [1], [2] to make properties
non-writable and non-configurable (i.e., can't be written, can't be
deleted or configured to make it writable again etc.)
For example, the following
Object.defineProperty(this, "quit", { writable: false,
configurable: false })
will make quit function non-writable and non-configurable. You can do
the same for all builtin properties of global object just before
evaluating any other code:
(function() {
var keys = Object.getOwnPropertyNames(this)
for (var k in keys) {
Object.defineProperty(this, keys[k],
{ writable: false, configurable: false })
}
})()
quit = 4
print(typeof quit)
print(quit)
Java = "hello"
print(typeof Java)
print(Java)
[1]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
[2] http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.6
Hope this helps,
-Sundar
On 3/1/2016 7:13 AM, Trig Chen wrote:
> I'm using nashorn engine in embedding mode and providing user a command
> line textbox to interactive with nashorn. It's fund that nashorn engine's
> built-in functions or objects such as quit, Java were overwritten by user's
> mistaken typing:
>
> quit=3; Java="Hello";
>
> Is there a way to prevent user overwrite the built-in functions, objects
> and java objects exposed to nashorn engine?
More information about the nashorn-dev
mailing list