Some projects use Object.create() or Object.defineProperties() function. I wonder is is recommended? Whats the difference between
x = Object.create(null);
vs
x = {}
And
x = {}
x.__proto__.hello = function() {
console.log("hello");
}
vs
x = Object.create(null);
Object.defineProperty(x, "hello", {
value: function() {
console.log("hello");
}
});
defineProperty/create seems very verbose and long to me. When/Why do I use them? Perhaps the good might be to enforce getters/setters/overriding properties?
There is a huge difference. Have a look at the docs!
Object.createdoes create an Object that inherits from the first argument,nullin your case. In contrast,{}– ornew Object()– creates a new object that inherits fromObject.prototype.__proto__is non-standard and should not be used. However, in your case you just doObject.prototype.hello = function() {…};. Never extend that object with enumerable properties, never ever!Object.definePropertydoes define a property on an object with a special descriptor object. Theenumerable,configurableandwritableattributes default tofalse, which means that you wont be able todelete x.hellofor example, or assign any other value.Your first snippet creates a plain object, which inherits a
hellomethod fromObject.prototype, while your second snippet creates an object inheriting from nothing and having a non-editablehelloproperty. I don’t see much relatedness.