我已经完成了这个功能:
var changeFilter = ( function (filterName, filterValue) {
var filters = {
"tip-oglasa": "",
"zemlja": "",
"grad": "",
"deo-grada": "",
"min-kvadrata": "",
"max-kvadrata": "",
"min-soba": "",
"max-soba": "",
"min-spratova": "",
"max-spratova": "",
"min-godina-izgradnje": "",
"max-godina-izgradnje": ""
};
return function () {
filters[filterName] = filterValue;
return filters;
};
})();
我希望有一个函数,在其中定义对象filters
,并通过两个函数(getFilters
获取/更改它,这将只是得到过滤器变量和{<1}}将更改过滤器变量和会返回结果。)
是否可以做这样的事情?我不希望将changeFilter
对象公开,因为我只想通过这两种方法访问它。
答案 0 :(得分:1)
当然,只需返回一个带有函数的对象文字,它将充当方法:
var filtersProxy = ( function () {
var filters = {
"tip-oglasa": "",
"zemlja": "",
"grad": "",
"deo-grada": "",
"min-kvadrata": "",
"max-kvadrata": "",
"min-soba": "",
"max-soba": "",
"min-spratova": "",
"max-spratova": "",
"min-godina-izgradnje": "",
"max-godina-izgradnje": ""
};
return {
getFilters: function getFilters() {
return filters;
},
changeFilter: function changeFilter(filterName, filterValue) {
filters[filterName] = filterValue;
return filters;
}
};
})();
有关此特定示例的一些注意事项:
filtersProxy.getFilters()
将直接返回对filters
对象的引用,对此对象的更改将通过filters
变量反映出来。也就是说,有人可以做filtersProxy.getFilters().foo = 'bar'
并改变它。可能的解决方案:
filters
。getFilter(key)
,它返回指定对象属性的值。filtersProxy.changeFilter()
遇到同样的问题,返回filters
。在这里,您只需return this
即可返回代理对象,并允许链接:filtersProxy.changeFilter('foo', 'bar').changeFilter('bar', 'baz').getFilter('baz')
。changeFilter
方法,就像它们真正属于的那样。答案 1 :(得分:0)
当然,例如,您可以使用变量“private”,或者只能使用var
在函数范围内访问,然后让getter和setter根据需要更改该变量:
function Filter() {
var filters = {
"tip-oglasa": "",
"zemlja": "",
"grad": "",
"deo-grada": "",
"min-kvadrata": "",
"max-kvadrata": "",
"min-soba": "",
"max-soba": "",
"min-spratova": "",
"max-spratova": "",
"min-godina-izgradnje": "",
"max-godina-izgradnje": ""
};
this.setFilter = function(filter, value){
filters[filter] = value;
}
this.getFilter = function(){
return filters;
}
}
var filter = new Filter();
console.log(Filter.filters); // private, shows undefined
console.log(filter.getFilter()); // show filter
filter.setFilter("grad", "foo"); // set grad filter to "foo"
console.log(filter.getFilter()); // shows updated filter