12

カスタム属性、つまり、標準以外の属性を持つプロパティ記述子を使用して JavaScript プロパティを定義したいと思いますvaluewritableなど...

以下の例では、カスタム属性を持つプロパティ記述子でプロパティを定義していますcustomAttr。への呼び出しは正常にObject.defineProperty機能しますが、後でプロパティ記述子の属性をループしようとすると、カスタム属性がリストされません。

私がやろうとしていることは可能ですか?

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

4

2 に答える 2

8

いいえ、できません。これは何をするかObject.definePropertyです:

...

 3. Attributesを引数として呼び出した結果を desc とします。ToPropertyDescriptor

4. O の [[DefineOwnProperty]] 内部メソッドを引数namedesc、および true で呼び出します。

 5. Oを返します。

つまり、ToPropertyDescriptor「列挙可能」、「書き込み可能」、「構成可能」、「値」、「取得」、または「設定」ではないものはすべて無視されます。

  1. ...

  2. 最初はフィールドを持たない新しいプロパティ記述子を作成した結果をdescとします。

  3. Objの [[HasProperty]] 内部メソッドを引数 " enumerable" で呼び出した結果が true の場合、
    • ...

(他の有効な記述子プロパティについて手順 3 を繰り返します)

 10.返品について

于 2013-02-28T13:55:31.747 に答える
4

Resurrecting an old post here, but I found the idea interesting. You can extract the fact that functions are objects in javascript, and use the get function as the attribute holder :

function setPropertyAttribute(obj, propertyName, attributeName, attributeValue) {
  var descriptor = getCustomPropertyDescriptor(obj, propertyName);

  descriptor.get.$custom[attributeName] = attributeValue;
}

function getPropertyAttributes(obj, propertyName) {
  var descriptor = getCustomPropertyDescriptor(obj, propertyName);

  return descriptor.get.$custom;
}

function getPropertyAttribute(obj, propertyName, attributeName) {
  return getPropertyAttributes(obj, propertyName)[attributeName];
}

function getCustomPropertyDescriptor(obj, prop) {
  var actualDescriptor = Object.getOwnPropertyDescriptor(obj, prop);
  if (actualDescriptor && actualDescriptor.get && actualDescriptor.get.$custom) {
    return actualDescriptor;
  }

  var value = obj[prop];
  var descriptor = {
    get: function() {
      return value;
    },
    set: function(newValue) {
      value = newValue;
    }
  }
  descriptor.get.$custom = {};

  Object.defineProperty(obj, prop, descriptor);
  return Object.getOwnPropertyDescriptor(obj, prop);
}

Then :

var obj = {
  text: 'value',
  number: 256
}

setPropertyAttribute(obj, 'text', 'myAttribute', 'myAttributeValue');

var attrValue = getPropertyAttribute(obj, 'text', 'myAttribute'); //'myAttributeValue'

fiddle here.

于 2017-06-12T02:19:29.577 に答える