Within your function:
var x = function(){
var result = 5,
clear = function(){
result = 0;
The identifier result in this function has a closure to the variable result in the outer function (i.e. outer execution context).
};
return {
result: result,
That assigns the value of the variable named result to the object property named result.
clear: clear
}
}
So later when you call y.clear() you are setting the value of the variable held in the closure, which does not update the object property named result.
If you want x to be a constructor, then:
function X() {
this.result = 5;
this.clear = function() {
this.result = 0;
}
}
So now:
var y = new X();
y.clear();
console.log(y.result); // 0
Note that it is convention for constructors to have a name starting with a capital letter. You can learn more about how to use the new operator on MDN.
To leverage ECMAScript inheritance, put the clear function on the constructor's prototype so that all instances inherit the one method, rather than each having its own:
function X() {
this.result = 5;
}
X.prototype.clear = function() {
this.result = 0;
}
resulton top is not the same asresultin the object you're returning. Make a getter function.var y = x();, notvar y = new x();.xis not a constructor function. (It does not write tothis.)clearis a setter because it sets theresultvariable. A getter would return theresultvariable.