gpt4 book ai didi

javascript - 服务中的只读属性

转载 作者:行者123 更新时间:2023-11-28 15:18:09 25 4
gpt4 key购买 nike

我有一个缓存服务,我想在其中存储数据。

angular.module('core').service('markerCache', function(){
var cache = [];
this.set_cache = function(arr){
cache = arr;
this.cached = true;
};
this.cached = false; //this must be read-only and must be property, not function
});

如果可能的话,我还想在 Angular 服务(工厂,服务)中定义只读(值只能在服务内部设置)属性,如果没有 - 任何解决方法都会很棒。
There is一种在 JavaScript 中定义只读属性的方法,但如何以 Angular 方式实现呢?
我所说的只读是指在服务内设置值。例如

angular.module('core').controller('Ctrl', function($scope, markerCache){
markerCache.cached = false; //disable setter outside of markerCache service
});

更新,对于那些仍然感兴趣的人,这里是工作服务

angular.module('core').service('markerCache', function(){
var cache = [];
var cached = false;
Object.defineProperty(this, "cache", {
get: function() {
return cache;
},
set: function(val){
cache = val;
cached = true;
}
});
Object.defineProperty(this, "cached", {
get: function() {
return cached;
},
set: angular.noop
});
});

最佳答案

您可以使用闭包隐藏变量并使用 Object.defineProperty 公开属性读取变量。

angular.module('core').service('markerCache', function(){
var cache = [];
var cached = false; // private variable
this.set_cache = function(arr){
cache = arr;
cached = true;
};
Object.defineProperty(this, "cached", { // public readonly getter
get: function() {
return cached;
},
set: function(val) {
//throw new Error('Cannot set internal cache state'); //throw custom exception
}
//set: angular.noop //or do nothing, empty setter
})
});

关于javascript - 服务中的只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32708688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com