有没有办法冻结ES6地图? [英] Is there a way to freeze an ES6 Map?
问题描述
我正在寻找冻结本机ES6地图的方法.
I'm looking for a way to freeze native ES6 Maps.
Object.freeze
和 Object.seal
似乎没有工作:
Object.freeze
and Object.seal
don't seem to work:
let myMap = new Map([["key1", "value1"]]);
// Map { 'key1' => 'value1' }
Object.freeze(myMap);
Object.seal(myMap);
myMap.set("key2", "value2");
// Map { 'key1' => 'value1', 'key2' => 'value2' }
这是预期的行为,因为objects
和maps
的冻结冻结属性不是objects
,或者这可能是错误/尚未实现?
Is this intended behavior since freeze freezes properties of objects
and maps
are no objects
or might this be a bug / not implemented yet?
是的,我知道,我可能应该使用 Immutable.js ,但是有没有ES6 Maps做到这一点的方法?
And yes I know, I should probably use Immutable.js, but is there any way to do this with native ES6 Maps?
推荐答案
@loganfsmyth ,您的回答给了我一个主意,那呢:
@loganfsmyth, your answer gave me an idea, what about this:
function freezeMap(myMap){
if(myMap instanceof Map) {
myMap.set = function(key){
throw('Can\'t add property ' + key + ', map is not extensible');
};
myMap.delete = function(key){
throw('Can\'t delete property ' + key + ', map is frozen');
};
myMap.clear = function(){
throw('Can\'t clear map, map is frozen');
};
}
Object.freeze(myMap);
}
这对我来说非常合适:)
This works perfectly for me :)
在注释中更新了 @Bergi 中的点:
Updated with points from @Bergi in the comments:
var mapSet = function(key){
throw('Can\'t add property ' + key + ', map is not extensible');
};
var mapDelete = function(key){
throw('Can\'t delete property ' + key + ', map is frozen');
};
var mapClear = function(){
throw('Can\'t clear map, map is frozen');
};
function freezeMap(myMap){
myMap.set = mapSet;
myMap.delete = mapDelete;
myMap.clear = mapClear;
Object.freeze(myMap);
}
这篇关于有没有办法冻结ES6地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!