Subj : Re: named scope To : Stuart From : Igor Bukanov Date : Mon Aug 23 2004 11:15 pm Stuart wrote: > Igor, > > Thanks, your reply was very helpfull. To clarify my first question what I > am trying to do is support something like: > > I have various variable scopes, namely: session, document and anonymous. If > there was a variable declared with session scope (e.g var x = 2) there could > be some script at an anonymous scope which could use this variable in one of > two ways e.g. > > > var y = x + 5 > > -or- > > var y = session.x + 5 > > I am not sure how to support this. To make this create a scope object for your anonymous scope, set its parent scope to null and point its prototype to document scope. The document scope can in turn point to the session scope which can either host the standard library objects or point via its prototype to the library objects. The session scope can alias itself under "session" property like in: ScriptableObject.putProperty(sessionScope, "session", sessionScope); Then all new variables (with or without var) will be added to anonymous scope while "session." prefix can still be explicitly used to access session objects if they are hidden behind anonymous scope names. > > I addition to figuring out how to do the above I'd like to ask a follow up > question regarding your reply. The link you gave me had some code snippets > e.g.: > > Context cx = Context.enter(); > try { > Scriptable windowJS = Context.toObject(window, libraryScope); > windowJS.setParent(null); > windowJS.setPrototype(libraryScope); > documentScope = cx.newObject(windowJS); > documentScope.setParent(null); > documentScope.setPrototype(windowJS); > ScriptableObject.putProperty(documentScope, "window", > documentScope); > ScriptableObject.putProperty(documentScope, "self", > documentScope); > } finally { Context.exit(); > } > > All of these code snippets used the setPrototype() rather than setParent(). > Perhaps my confusion is caused by my first question (session.x) but when > would you use setParent() rather then setPrototype()? Is the only > difference the scope in which the new variable would get created (if you did > not use the var)? Effectively the answer is yes but name access is faster if the initial scope is already top scope. .