myAcessors
is an object containing the properties getData
and setData
, they are both functions.
myAcessors = (function() {
var data = "data";
var getData = function() {
console.log(data);
};
var setData = function(val) {
data = val;
};
return {
getData: getData,
setData: setData
};
})();
For example, you can call myAcessors.getData()
and it will return "data"
.
By using an anonymous function your enclosing all code inside the brackets. Notice that myAcessors.data
will not return anything. This is because variable data lives inside of the anonymous function and cannot escape unless you provide a way to: i.e. a get method. In your case, you do have a get method: getData
that will return variable from within the closure.
You could say your properties are private, because they cannot be accessed without a get method.
A more common way of declaring an object in JavaScript is with:
myAcessors = {
data: "data",
getData: function() {
console.log(this.data)
},
setData: function(data) {
this.data = data
}
}
But here myAcessor.data
would indeed return the property. Unlike the other object this time you can access all of myAcessor
's properties outside the object.