If I have an application with a bunch of getters and setters, then I think that I need to use closures to keep the value of the setter, don't I?
Here's what I've got so far, but I think these two methods should be returning functions (closures). I don't think I should be using this.local.result because the two will conflict.
myApplication = function(){
this.local = {};
};
myApplication.prototype.myFirstMethod = function(){
if (arguments.length) {
this.local.result = arguments[0];
} else {
return this.local.result;
}
};
myApplication.prototype.mySecondMethod = function(){
if (arguments.length) {
this.local.result = arguments[0];
} else {
return this.local.result;
}
};
var app = new myApplication();
app.myFirstMethod(1);
result = app.myFirstMethod();
console.log(result);
The purpose of using closures is to keep the variable private (not directly accessible from the global scope).
Here is how to use a closure:
myApplication.prototype.myFirstMethod = (function () {
var data = '';
return function () {
if (arguments.length) {
data = arguments[0];
} else {
return data;
}
}
})();
If you dont need the data to be private, you can simply do this:
myApplication.prototype.myFirstMethod = function(){
if (arguments.length) {
this.local['firstData'] = arguments[0];
} else {
return this.local['firstData'];
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.