Reputation: 23
I'm a C/Python
guy, shifted to 'Javascript' recently.
Basically, I receive an object (named context
) in a function as an argument.The caller function's definition is hidden to me. Now I need to add a field(type
) to the context
. When I add type
to context directly, it doesn't reflect changes in 'context'. But when I try to modify the value of one of the existing field of 'context', this change is reflected.
Then I create one more object(new_obj
) and copy 'context' in the 'new_object', then tried to add the field in the 'new_object', but unsuccessful. So from this behaviour, I guess the value is not copied but the reference is.
So finally I need to copy field by field in the new_obj
and then add the new field 'type'. Also if I create a local object, then new fields are being added and object structure is modified.
So far so good. But I was wondering about the implementation of the 'context' object in background caller function. I mean if there is some 'const' type thing here(as in C, (Random thoughts :P)), then at what level it is applied i.e. there is only restriction of adding new fields or also of changing values of the existing fields. Needed some light over this issue.
Upvotes: 0
Views: 48
Reputation: 1074989
But I was wondering about the implementation of the 'context' object in background caller function. I mean if there is some 'const' type thing here(as in C, (Random thoughts :P)), then at what level it is applied i.e. there is only restriction of adding new fields or also of changing values of the existing fields. Needed some light over this issue.
It depends partially on whether the object is a host-provided object (e.g., from the browser or similar), or a true JavaScript object.
A host-provided object can do very nearly anything it wants. :-)
A true JavaScript object can be "sealed" via Object.seal
. That prevents new properties being added to it, but doesn't prevent changes to existing properties — exactly matching your description of context
. Here's an example:
var o = Object.seal({
answer: 0
});
console.log(o.answer); // 0
o.answer = 42;
console.log(o.answer); // 42
o.question = "Life, the Universe, and Everything";
console.log(o.question); // undefined
If you use strict mode, trying to create a property on a sealed object is a 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, the Universe, and Everything"; // Throws error
console.log(o.question); // (we don't get here)
Upvotes: 2