Reputation: 13713
Can I safely assume that in any implementation of JavaScript,
1.) for any object generated by the var obj = { ... };
construct, obj[s]
is undefined
for any string s
unless obj[s]
has been explicitly set by my own code?
2.) if typeof obj === 'object'
(and obj
does not stem from some global, pre-defined variable or function in the global namespace), Object.hasOwnProperty(obj, s)
is false
for any string s
except when I have set property s
explicity before or, maybe, when Array.isArray(obj)
is true
?
In short: Can I assume that user-generated objects that are neither arrays nor of function type do not have pre-defined own properties?
Background: I need to write an interpreter for a very tiny subset of JavaScript that should safely execute user code. I would like to leverage on the optimization capabilities of the JavaScript engine. Hence I am planning to (1.) parse the user's code, (2.) re-write the AST such that (a) no global names can be accessed, (b) property access is restricted by a construct like ((typeof obj === 'object') && Object.hasOwnProperty(obj, s)) ? obj[s] : undefined
, (3.) eval
the re-written code. For this to work, it is necessary for the object
s not to have predefined properties like, e.g., (function () {}).caller
, as otherwise the user could make my interpreter to execute arbitrary code or mess with the global objects of my environment in general.
Does, maybe, anybody know of a package where something like this has been done already? My requirements are not high: I need to execute user code, the user needs to work with numbers, strings, arrays, objects, and functions, and I need to exchange these things with the user code.
Edit: First assumption is wrong, see answers.
Upvotes: 0
Views: 64
Reputation: 780889
You can't assume #1. obj[s]
will access inherited properties, not just own properties.
var obj = {a: 1, b: 2}
console.log(obj["__proto__"] === undefined);
console.log(obj["toString"] === undefined);
I think #2 is a safe assumption. The whole point of hasOwnProperty()
is to distinguish inherited properties from properties that were assigned explicitly in the object.
Upvotes: 3