0

一些项目使用Object.create()Object.defineProperties()功能。我想知道是推荐的吗?有什么区别

x = Object.create(null); 

对比

x = {}

x = {}
x.__proto__.hello = function() { 
    console.log("hello"); 
}

对比

x = Object.create(null);
Object.defineProperty(x, "hello", { 
    value: function() { 
        console.log("hello"); 
    } 
});

defineProperty/create对我来说似乎非常冗长和冗长。我何时/为什么使用它们?也许好的可能是强制执行 getter/setter/overriding 属性?

4

1 回答 1

0

这是个很大的差异。看看文档!

  • Object.create在您的情况下,确实会创建一个继承自第一个参数的对象null。相反,{}- 或new Object()- 创建一个继承自 的新对象Object.prototype
  • __proto__是非标准的,不应使用。但是,在您的情况下,您只需执行Object.prototype.hello = function() {…};. 永远不要用可枚举的属性扩展该对象,永远不要!
  • Object.defineProperty确实在具有特殊描述符对象的对象上定义了一个属性。enumerable和属性默认为configurable,这意味着您将无法例如或分配任何其他值。writablefalsedelete x.hello

您的第一个片段创建了一个普通对象,该对象继承了一个hello方法Object.prototype,而您的第二个片段创建了一个从无继承并具有不可编辑hello属性的对象。我没有看到太多的相关性。

于 2012-12-05T08:45:47.650 回答