应该为私有变量使用getter和setter方法吗? [英] Should one use getters and setters for private variables?
本文介绍了应该为私有变量使用getter和setter方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用这样的JavaScript对象:
I'm using JavaScript objects like this:
var obj = new Foob;
我应该假装有一种私人方式来做吗?
should I pretend like there is a private way and do:
obj.get('foo');
或者我应该尝试直接以方式访问:
or should I just try to access directly as :
obj.foo
推荐答案
实际上,您可以拥有只能通过Java语言中的setter和getter访问的变量:
You can actually have variables which can only be accessed through setters and getters in Javascript:
function Foob(){
var foo = 5;
this.getFoo = function(){
return foo;
}
this.setFoo = function(newFoo){
foo = newFoo;
return this;
}
}
var obj = new Foob;
obj.getFoo(); // 5
obj.foo; // undefined
或者如果您想要通用的获取/设置器:
Or if you want a generic getter/setter:
function Foob(){
// You can set default values in the data object
var data = {};
this.get = function(key){
return data[key];
}
this.set = function(key, value){
data[key] = value;
return this;
}
}
这篇关于应该为私有变量使用getter和setter方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文