在 JavaScript 中,通常使用对象作为哈希:
hash = {};
hash.key = 'value';
甚至可以使用带空格的键:
hash['a key'] = 'a value';
但有几个限制:不得调用 key
__proto__
,构造函数
,hasOwnProperty
,isPrototypeOf
,propertyIsEnumerable
,toLocalString
,toString
,valueOf
,__defineGetter__
,__defineSetter__
,__lookupGetter__
,__lookupSetter__
,
因为这会导致命名空间与 JavaScript 对象内部发生冲突。
规避此限制的最佳解决方案是什么?
最佳答案
例如,您可以使用Object.create
并将parent设置为null
var data = {};
console.log(
data.toString
); // in parent prototype there is toString method. returns function
var hash = Object.create(null);
console.log(
hash.toString,
hash.valueOf,
hash.__defineGetter__
); // will be undefined because we set parent as null
关于javascript - 如何在 Javascript 中获取哈希表或记录类型而不发生任何 namespace 冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34183046/