[英]Using prototype to define a getter/setter
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? 如果我的应用程序中有很多getter和setter,那么我认为我需要使用闭包来保持setter的价值,不是吗?
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.
我认为我不应该使用this.local.result,因为两者会发生冲突。
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'];
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.