Consider this simple JavaScript module pattern:
var human = (function () {
var _name = '';
return {
name: _name,
setName: function (name) {
_name = name;
}
}
})();
human.setName('somebody');
alert(human.name); // shows an empty string
human = (function () {
var _name = '';
return {
name: function() {
return _name;
},
setName: function (name) {
_name = name;
}
}
})();
human.setName('somebody');
alert(human.name()); // shows 'somebody'
Why the second closure works fine, while the first closure is not working? See example here.
Please also see this fiddle, which proves that simple properties can be used instead of getter functions.
In Javascript
As name is a string
name: _namewill store the current value of_nameand not the reference to_name.setNamein your example will modify only_name.getNamewill access_namewhich holds the current value..namewill access the copied value which was set during the initialisation (name: _name).See also SO: Javascript by reference vs. by value