Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Object.getOwnPropertyDescriptors(O)

Object.getOwnPropertyDescriptors(O)

When the getOwnPropertyDescriptors function is called, the following steps are taken:

  1. Let obj be ToObject(O).
  2. ReturnIfAbrupt(obj).
  3. Let keys be the result of calling the [[OwnPropertyKeys]] internal method of obj.
  4. ReturnIfAbrupt(keys).
  5. Let descriptors be the result of the abstract operation ObjectCreate with the intrinsic object %ObjectPrototype% as its argument.
  6. Let gotAllNames be false.
  7. Repeat while gotAllNames is false, 1. Let next be the result of IteratorStep(keys). 1. ReturnIfAbrupt( next ). 1. If next is false, then let gotAllNames be true. 1. Else,
    1. Let nextKey be IteratorValue(next).
    2. Let nextKey be ToPropertyKey(nextKey).
    3. ReturnIfAbrupt(nextKey).
    4. Let desc be the result of calling the [[GetOwnProperty]] internal method of obj with argument nextKey.
    5. ReturnIfAbrupt(desc).
    6. Let descriptor be FromPropertyDescriptor(desc).
    7. ReturnIfAbrupt(descriptor).
    8. Let status be the result of CreateDataProperty(descriptors, nextKey, descriptor).
    9. Assert: status is not an abrupt completion.
  8. Return descriptors.
@WebReflection

This comment has been minimized.

Copy link
Owner Author

commented Mar 5, 2014

note: to give right credits, this came out from a previous revision proposed by anba

example: a polyfill that works already in ES5 can be found here

@rauschma

This comment has been minimized.

Copy link

commented Dec 27, 2015

Would you mind adding an example? I always find those tremendously helpful in proposals.

@WebReflection

This comment has been minimized.

Copy link
Owner Author

commented Jan 18, 2016

Shallow copy

let shallowCopy = Object.create(
  Object.getPrototypeOf(originalObject),
  Object.getOwnPropertyDescriptors(originalObject)
);

"Real" Mixins usable with classes prototypes too.

let mix = (object) => ({
  with: (...mixins) => mixins.reduce(
    (c, mixin) => Object.create(
      c, Object.getOwnPropertyDescriptors(mixin)
    ), object)
});

let a = {a: 'a'};
let b = {b: 'b'};
let c = {c: 'c'};
let d = mix(c).with(a, b);

Polluting

Object.defineProperties(
  target,
  Object.getOwnPropertyDescriptors(source)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.