Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way of using property descriptors in Object.create?

I passed an object as the second parameter in the Object.create method, but I'm getting the following error:

Uncaught TypeError: Property description must be an object: 1

Here's the faulty code:

var test = Object.create(null, {
    ex1: 1,
    ex2: 2,
    meth: function () {
        return 10;
    },
    meth1: function () {
        return this.meth();
    }
});
like image 251
Brandon Avatar asked Jun 07 '16 07:06

Brandon


People also ask

What is an object property descriptor?

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions.

How do you create property of objects?

One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.

What is the correct way to create an object in JavaScript?

To create an object, use the new keyword with Object() constructor, like this: const person = new Object(); Now, to add properties to this object, we have to do something like this: person.


1 Answers

Object.create(proto, props) has two arguments:

  1. proto — the object which should be the prototype of the newly-created object.
  2. props (optional) — an object whose properties specify property descriptors to be added to the newly-created object, with the corresponding property names.

The format for the props object is defined here.

In short, the available options for each property descriptor are these:

{
    configurable: false, // or true
    enumerable: false, // or true
    value: undefined, // or any other value
    writable: false, // or true
    get: function () { /* return some value here */ },
    set: function (newValue) { /* set the new value of the property */ }
}

The problem with your code is that the property descriptors you've defined are not objects.

Here's an example of a proper usage of property descriptors:

var test = Object.create(null, {
    ex1: {
        value: 1,
        writable: true
    },
    ex2: {
        value: 2,
        writable: true
    },
    meth: {
        get: function () {
            return 'high';
        }
    },
    meth1: {
        get: function () {
            return this.meth;
        }
    }
});
like image 185
Dmytro Shevchenko Avatar answered Oct 13 '22 13:10

Dmytro Shevchenko