Why can't I redefine a property in a Javascript object?

前端 未结 4 1485
日久生厌
日久生厌 2020-12-08 13:50

I am creating a object using Object.create and I want to add properties to it.

> var o = Object.create({});
undefined

> Object.defineProp         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 14:00

    1. Properties defined through Object.defineProperty() are, by default, non-configurable.

      To allow them to be redefined, or reconfigured, they have to be defined with this attribute set to true.

      var o = Object.create({});
      
      Object.defineProperty(o, "foo", {
          value: 42,
          enumerable: true,
          configurable: true
      });
      
      console.log(o); // { foo: 42 }
      
      Object.defineProperty(o, "foo", {
          value: 45,
          enumerable: true,
          configurable: true
      });
      
      console.log(o); // { foo: 45 }
      

    2. o.prototype is undefined because objects don't typically have prototype properties.

      Such properties are found on constructor functions for new instances to inherit from, roughly equivalent to:

      function Foo() {}
      
      //  ... = new Foo();
      var bar = Object.create(Foo.prototype);
      Foo.call(bar);
      

      Object are, however, aware of their prototype objects. They're referenced through an internal [[Prototype]] property, which __proto__ is/was an unofficial getter/setter of:

      console.log(o.__proto__); // {}
      

      The standardized way to read the [[Prototype]] is with Object.getPrototypeOf():

      console.log(Object.getPrototypeOf(o)); // {}
      

提交回复
热议问题