How to create variables that can be accessed globally but can be modified only by a certain function?
-
4you can't do that – Jaromanda X Sep 08 '17 at 12:57
2 Answers
Now with ecma 6 you can declare global variable with the keyword const, and these variables won't be modified.
const VARIABLE="wont be modified";
Moreover every time you create a function a closure is created. A closure is an inner function that has access to the outer function's variables, so you can create a function and work with it's closure
(function(global){
var a="I'm a";
function modifyA(newvalue){
a=newvalue;
}
function getA(){
return a;
}
global.modifyA=modifyA;
global.getA=getA;
})(window);
console.log(typeof a,"a doesn't exist in global environment");
console.log(getA(),"but exist in getA's closure");
modifyA('I have a new value');
console.log(getA(),"A can only be modify it with modifyA function");

- 7,486
- 2
- 22
- 37
One way to accomplish something similar is to create a local function that would set the value and create a new 'get' function to return the value like:
function createObjectGetter(obj)
{
this.getObject = function() { return obj; };
}
Then when you call it like createObjectGetter("abc")
, from that point you can fetch the object like getObject()
which will return "abc"
while the value stays constant and is only adjustable through createObjectGetter()
method.
Here's a reference: How can you make a variable/Object read only in Javascript?

- 1,462
- 12
- 23