Object.create method in javascript

Being new to javascript, I tried to understand the Object.create () method here

https://developer-new.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create

In the sample code, line 18. The accessor property is created with the ability to write to true. I also read that writing is only available for data descriptors.

Chasing away

var o = Object.create(Object.prototype, { // foo is a regular "value property" foo: { writable:true, configurable:true, value: "hello" }, // bar is a getter-and-setter (accessor) property bar: { writable: true, configurable: false, get: function() { return 10 }, set: function(value) { console.log("Setting `o.bar` to", value) } } }); console.log(o); 

I get invalid property error .

+6
source share
2 answers

The problem is that writable and set / get are mutually exclusive. The code generates this useful error in Chrome:

 Invalid property. A property cannot both have accessors and be writable... 

This makes logical sense: if you have set / get attributes for a property, this property will never be written and / or read, because any attempts to read / write it will be intercepted through access functions. If you define a property as writable and provide access functions to it, you simultaneously say:

  • "The value of this property can be directly changed" and
  • "Block all attempts to read and / or write to this property, use these functions instead."

A mistake just stops you from indicating a contradiction. I suppose from the fact that you wrote a getter and setter, you really don't want the property to be writable . Just delete this line and your code works just fine.

+12
source

Late answer, not looking for a voice, but hoping that it will be useful.

There are two types of properties. Each property is equal to:

  • a data property that has the following four attributes:

    • value
    • record
    • are enumerable
    • configurable
  • OR an accessor property that has the following four attributes:

    • receive
    • to establish
    • are enumerable
    • configurable

Therefore, there is no property that can have both get and writable . This is just JavaScript! See Section 8.6 ECMAScript Standard for details.

+10
source

Source: https://habr.com/ru/post/921455/


All Articles