JS: How to Create Object with Parent X?

By Xah Lee. Date: . Last updated: .

There are several ways to create a object with a specified parent object.

Object Literal Expression

obj = {__proto__:my_parent_obj, more_properties}

const e1 = {p:7};

// create object with e1 as parent, and a property x
const e2 = {__proto__:e1, x:8};

console.log( e2 ); // { x: 8 };

console.log (
    Object.getPrototypeOf ( e2 ) === e1
); // true

[see JS: Object Literal Expression]


var obj = Object.Create(my_parent)

[see JS: Object.create]

With Constructor

Use a constructor, by the following steps:

  1. Define a function F with no return statement.
  2. Set the prototype property: F.prototype = my_parent
  3. Create the object. var obj = new F.

[see JS: Operator “new”]

[see JS: How to Use Object.create() to Emulate Constructor?]

Set Prototype

Note, you can always create a object first then change/set its parent.

[see JS: Get/Set Prototype]

Object and Inheritance Topic

  1. JS: Object System Overview
  2. JS: What's Object?
  3. JS: Prototype and Inheritance
  4. JS: Create Object
  5. JS: Object Literal Expression
  6. JS: Get/Set Prototype
  7. JS: How to Create Object with Parent X?
  8. JS: Prevent Adding Property
  9. JS: Determine Type of Object
  10. JS: Primitive Value Object Wrapper
  11. JS: Clone, Deep Copy Object/Array
  12. JS: Test Equality of Objects

  1. JS: Object Object
  2. JS: Object.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon