Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do JavaScript property descriptors support custom attributes?

Tags:

javascript

I would like to define a JavaScript property using a property descriptor that has custom attributes, in other words, attributes other than the standard value, writable, etc...

In the example below I have defined a property with a property descriptor that has the custom attribute customAttr. The call to Object.defineProperty works fine but later when I try to loop over the attributes of the property descriptor, my custom attribute is not listed.

Is what I am trying to do possible?

const o = {}

Object.defineProperty(o, 'newDataProperty', {
  value: 101,
  writable: true,
  enumerable: true,
  configurable: true,
  customAttr: 1,
})

const desc = Object.getOwnPropertyDescriptor(o, 'newDataProperty')

// List the descriptor attributes.
for (const prop in desc) {
  console.log(`${prop}: ${desc[prop]}`)
}

// PROBLEM: `customAttr` is not listed
like image 252
user2073948 Avatar asked Feb 28 '13 13:02

user2073948


1 Answers

No, it's not possible. This is what Object.defineProperty does:

...

 3. Let desc be the result of calling ToPropertyDescriptor with Attributes as the argument.

 4. Call the [[DefineOwnProperty]] internal method of O with arguments name, desc, and true.

 5. Return O.

And in short, ToPropertyDescriptor simply ignores anything that's not "enumerable", "writable", "configurable", "value", "get" or "set":

  1. ...

  2. Let desc be the result of creating a new Property Descriptor that initially has no fields.

  3. If the result of calling the [[HasProperty]] internal method of Obj with argument "enumerable" is true, then
    • ...

(repeat step 3 for other valid descriptor properties)

 10. Return desc.

like image 169
James Allardice Avatar answered Nov 06 '22 21:11

James Allardice