Subj : Re: Spidermonkey: error with const on second run of script To : Peter Paulus From : Brendan Eich Date : Wed Jul 23 2003 11:16 am Peter Paulus wrote: >Hello all, > >In own of my test-javascripts I'm using the line: > >const engine = Engine.getEngine(); // get first registered engine > >Engine is a custom class (JSClass) that I've build. > >When I run this script for the first time all seems to be okay. > >When I run the same script for the second time I get an error that a const >variable is redefined. > > That's because you haven't cleared the scope of the global object in which that const is defined by the first script execution, or alternatively discarded that object (letting it become collectible garbage) and made a new, empty one in which no such const already exists when the second execution runs. >Here's the code that runs the script (C++ wrapper around Spidermonkey) >void Context::runScriptFile(const char* source) >{ >jsval result; > >JSScript* script = JS_CompileFile(context, globalObj, source); >if (script) > { > JSBool ok = JS_ExecuteScript(context, globalObj, script, &result); > if (ok == JS_FALSE) > { > _STD::cout << "error in Context::runScriptFile()" << _STD::endl; > } > JS_DestroyScript(context, script); > } >} > >The context is not destroyed. How can I prevent this error? > Do you want to rerun the script on the same *object* (not context -- context is just for execution; objects at the end of the scope chain are where global variables and consts go)? If so, you may want to use JS_ExecuteScriptPart to run the prolog once only, and the main body as many times as you like. Or, use a new or cleared (JS_ClearScope) global object. /be .