When defining an object literal its possible to use a self-invoking function so the function has access to private variables,
JavaScript
x
9
1
obj={
2
value:(function(){
3
var private;
4
return function(){
5
return true;
6
}
7
}())
8
};
9
But is it possible to do the same thing with a getter/setter in an object literal?
JavaScript
1
9
1
obj={
2
get value(){
3
return value;
4
},
5
set value(v) {
6
value=v;
7
}
8
};
9
Advertisement
Answer
[edit 2022] A pretty old answer.
More actual: you can create a factory function. In the snippet the factory creates an object with (get and set) access (through the closure) to a private variable.
JavaScript
1
12
12
1
const obj1 = objFactory(`Hello`);
2
const obj2 = objFactory(`World`);
3
console.log(`${obj1.privateThing} ${obj2.privateThing}`);
4
obj1.privateThing = `Goodbye`;
5
console.log(`${obj1.privateThing} ${obj2.privateThing}`);
6
7
function objFactory(somethingPrivate) {
8
return {
9
get privateThing() { return somethingPrivate; },
10
set privateThing(value) { somethingPrivate = value; }
11
};
12
}
The old answer:
Not really. You can also create an Immediately Invoked Function Expression (IIFE) for obj
though:
JavaScript
1
16
16
1
obj = function(){
2
var privatething = 'hithere';
3
4
return {
5
get value() {
6
return privatething;
7
},
8
set value(v) {
9
privatething = v;
10
}
11
};
12
}();
13
obj.value; //=> 'hithere';
14
obj.value = 'good morning to you too';
15
obj.value; //=> 'good morning to you too'
16