3

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.

3 Answers 3

7

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"
    }
}
Sign up to request clarification or add additional context in comments.

Comments

6

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
    }
}

Comments

0
Object.prototype.test = 0;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.