I am not sure if I am getting it right.
This example is straight from MDN (Mozilla Developer Network):
var bValue;
Object.defineProperty(o, "b", {get : function(){ return bValue; },
set : function(newValue){ bValue = newValue; },
enumerable : true,
configurable : true});
What happens is – it creates a global variable named bValue, which is not done. I understand that this example only demonstrates the use and thus it is okay if it creates a global variable. But if I am going to use this in an application, I will modify it slightly, by adding the this keyword:
Object.defineProperty(o, "b", {get : function(){ return this.bValue; },
set : function(newValue){ this.bValue = newValue; },
enumerable : true,
configurable : true});
Now, the object o will have property b, and at the same time, it will also have another property bValue. The user (programmer) will be exposed only to ‘b’ and not to ‘bValue’ though he can still access bValue directly – I don’t see how it can be prevented.
I understand that the property b and the property bValue may not always be same, but b would depend on the value of bValue because the getter and setter allow us to pre-process bValue before assigning the value to b.
The main question is, am I getting it right? Or am I missing something here?
You seem to be looking for a closure. This is a coding pattern that enables you to use private variables and only expose what you want to expose (public variables).
It creates a function and executes it immediately. This seems useless, but since functions introduce a level of scoping,
bValueis not accessible anywhere but within the function this way.The
o.bproperty acts as a delegate between the developer and the value. You cannot accessbValueitself. (Though in this example the getter/setter obviously act such that they exactly do the same as usingbValuedirectly.)http://jsfiddle.net/W4CSE/2/