Question

Object.create works differently in Nodejs compared to FireFox.

Assume an object like so:

objDef = {
  prop1: "Property 1"
}

obj = {
  prop2: "Property 2"
}

var testObj = Object.create(obj, objDef);

The above javascript works perfectly in Mozilla. It basically uses the second argument passed to Object.create to set default values.

But this does not work in Node. The error I get is TypeError: Property description must be an object: true.

How can I get this to work in Node? I want to basically create an Object with a default value.

Was it helpful?

Solution

The second parameter should map property names to property descriptors, which are to be objects.

See the example shown at the MDN:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create#Using_%3CpropertiesObject%3E_argument_with_Object.create

You could solve by using something like this:

objDef = {
    prop1: {
        value: "Property 1"
    }
}

OTHER TIPS

The second parameter to Object.create(proto [, propertiesObject ]) should be a property descriptor object

The property descriptor structure is described here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty

This will create a property with a default value that can be both enumerated and modified:

Object.create(obj, {
    prop1: {
        configurable:true,
        enumerable:true,
        value:"Property 1",
        writable: true
    }
}
Object.prototype.test = 0;

will set the default value of test key in any object to 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top