First of all, functions are first class citizens in javascript.
So when you do
return function() {
console.log('return function() {');
if (arguments.length) {
console.log('setter: ' + x);
closure.result = x;
} else {
console.log('getter: ' + closure.result);
return closure.result;
}
}
This function is not executed, you are only returning as the value of your beep function.
So, in our case, the only code that really gets executed is :
var myApplication = {};
(function() {
function beep(x) {
console.log('x: ' + x);
}
myApplication.beep = beep;
})();
myApplication.beep(3);
RESULT = myApplication.beep();
In this case you are only logging the first argument passed to beep
, so 3
then undefined
.
Now for what you want to do here, no need to use closures, or prototypes :
var myApplication = {
x : null,
beep : function (x) {
if (typeof x != 'undefined') {
this.x = x;
} else {
return this.x;
}
}
};
// set x
myApplication.beep(3);
// get x
var x = myApplication.beep();
console.log('x :', x);
I would avoid messing with closures too early.