First of all, ECMA-Script 2015 and above has collections such as Map. That is, in new JavaScript implementations you no longer need to simulate dictionaries / hashmaps / hash tables with objects.
The article states that the great thing about bare objects is that you can use them as hashmaps without worrying about built-in objects such as toString, potentially causing errors when using a key with the same name.
, toString , , .
, , : var obj = { text: "Matias" };.
for..in Object.prototype, Object.keys :
Object.keys(obj).forEach(propertyName => {
var someOwnProperty = obj[propertyName ];
});
, for..in Object.keys Object.prototype.hasOwnProperty:
for(var propertyName in obj) {
if(obj.hasOwnProperty(propertyName)) {
// True if property is declared on obj and not in some
// level of the prototype chain
}
}
: @bergi -. obj hasOwnProperty, for..in , obj.hasOwnProperty Object.prototype.hasOwnProperty .
, , :
var obj = {
hasOwnProperty: "hey! I'm not Object.prototype.hasOwnProperty anymore!"
};
hasOwnProperty Object.prototype.hasOwnProperty.
Object.prototype.hasOwnProperty Function.prototype.call:
for(var propertyName in obj) {
if(Object.prototype.hasOwnProperty.call(obj, propertyName)) {
// True if property is declared on obj and not in some
// level of the prototype chain
}
}
Object.prototype.hasOwnProperty , if, this Function.prototype.bind:
var hasOwnProperty = Object.prototype.hasOwnProperty.bind(obj);
for(var propertyName in obj) {
if(hasOwnProperty(propertyName)) {
// True if property is declared on obj and not in some
// level of the prototype chain
}
}
Object.create(null), , - :
var bareObject = Object.create(null, {
text: { value: "hello world" }
});
var secondObject = Object.create(bareObject);
secondObject.text2 = "bye!";
for(var property in secondObject) {
}
, , in:
if("someProperty" in bareObject) {
}
Object.prototype.hasOwnProperty Function.prototype.call Function.prototype.bind, .
, , ES2015 , BabelJS, JavaScript .
ES5 / ES6? , , , ? - ?
Object.create ECMA- Script 5. , - NodeJS.