c++ - How can I make an object immutable in the Google V8 Javascript engine? -


is possible make object immutable in v8 javascript engine? v8 embedded in c++ application.

in case i've created , populated array (code simplified)

auto arr = v8::array::new(isolate, 10); (auto = 0; < 10; ++i) {     arr->set(context, i, v8::integer::new(isolate, i)); } 

i'd make resulting object "read-only" (as might calling object.freeze) before passing script. 1 of script authors got in confusing situation trying re-use object convoluted way, , i'd make harder happen making object immutable.

i understand can in javascript (object.freeze), able in c++ if possible.

this approach works, although it's little inelegant. essentially, i'm calling "object.freeze" directly in javascript, couldn't find way invoke functionality c++. i'm less fluent in v8, code may unnecessarily verbose.

/**  * make object immutable calling "object.freeze".  * https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/object/freeze  **/ void ezv8::utility::makeimmutable(v8::isolate * isolate, v8::local<v8::object> object) {     ezv8::ezv8 ezv8(isolate);     auto globaltmpl = v8::objecttemplate::new(isolate);     auto context = v8::context::new(isolate, nullptr, globaltmpl);      v8::isolate::scope scope(isolate);     v8::locker locker(isolate);     v8::handlescope scope(ezv8.getisolate());     v8::context::scope context_scope(context);      // define function "deepfreeze" listed on "object.freeze" documentation page cited above.     std::string code(         "function deepfreeze(obj) {\n"         "    var propnames = object.getownpropertynames(obj);\n"         "    propnames.foreach(function(name) {\n"         "        var prop = obj[name];\n"         "        if (typeof prop == 'object' && prop !== null)\n"         "            deepfreeze(prop);\n"         "    });\n"         "    return object.freeze(obj);\n"         "};");       v8::local<v8::string> source = v8::string::newfromutf8(isolate, code.c_str());      v8::local<v8::script> compiled_script(v8::script::compile(source));      // run script!     v8::local<v8::value> result = compiled_script->run();      v8::handle<v8::value> argv[]{ object };      v8::handle<v8::string> process_name = v8::string::newfromutf8(isolate, "deepfreeze");     v8::handle<v8::value> process_val = context->global()->get(process_name);       v8::handle<v8::function> process_fun = v8::handle<v8::function>::cast(process_val);     v8::local<v8::function> process = v8::local<v8::function>::new(isolate, process_fun);      // call script.     v8::local<v8::value> rv = process->call(context->global(), 1, argv); } 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -