javascript - How to be sure if a new field can be added to the pre-existing object or not? -
i'm c/python
guy, shifted 'javascript' recently.
basically, receive object (named context
) in function argument.the caller function's definition hidden me. need add field(type
) context
. when add type
context directly, doesn't reflect changes in 'context'. when try modify value of 1 of existing field of 'context', change reflected.
then create 1 more object(new_obj
) , copy 'context' in 'new_object', tried add field in 'new_object', unsuccessful. behaviour, guess value not copied reference is.
so need copy field field in new_obj
, add new field 'type'. if create local object, new fields being added , object structure modified.
so far good. wondering implementation of 'context' object in background caller function. mean if there 'const' type thing here(as in c, (random thoughts :p)), @ level applied i.e. there restriction of adding new fields or of changing values of existing fields. needed light on issue.
but wondering implementation of 'context' object in background caller function. mean if there 'const' type thing here(as in c, (random thoughts :p)), @ level applied i.e. there restriction of adding new fields or of changing values of existing fields. needed light on issue.
it depends partially on whether object host-provided object (e.g., browser or similar), or true javascript object.
a host-provided object can wants. :-)
a true javascript object can "sealed" via object.seal
. prevents new properties being added it, doesn't prevent changes existing properties — matching description of context
. here's example:
var o = object.seal({ answer: 0 }); console.log(o.answer); // 0 o.answer = 42; console.log(o.answer); // 42 o.question = "life, universe, , everything"; console.log(o.question); // undefined
if use strict mode, trying create property on sealed object handy error:
"use strict"; var o = object.seal({ answer: 0 }); console.log(o.answer); // 0 o.answer = 42; console.log(o.answer); // 42 o.question = "life, universe, , everything"; // throws error console.log(o.question); // (we don't here)
Comments
Post a Comment