0

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 objects 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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yet can I assume #1 if I re-state it to "for any object generated by the var obj = { ... }; construct, Object.hasOwnProperty(obj, s) ? obj[s] : undefined is undefined for any string s unless obj[s] has been explicitly set by my own code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.