JavaScript: How to Create Object with Parent X?

By Xah Lee. Date: . Last updated: .

Two ways to create a object with a specific parent.

Easy way: var obj = Object.Create(my_parent)

or, using 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.

Using Object.create()

The cleanest way to create a object with specified parent is Object.create(obj).

Object.create(obj) → return a new object such that its parent is obj.

// example of creating object with a specific parent object

// creating a object
var o1 = {};

// creating a object, with o1 as its parent
var o2 = Object.create(o1);

console.log(
    Object.getPrototypeOf(o2) === o1
); // true

Object.create() also takes a second argument for creating properties at the same time. See: JavaScript: Object.create

〔►see JavaScript: How to Use Object.create() to Emulate Constructor?

Using Constructor Function

Another way to create a object with a specified parent is by using a constructor function.

  1. Define a function F without return statement.
  2. Set F.prototype = parent where parent is the object you want to be the parent object.
  3. Use obj = new F(…) to create the new object.
// create a object with a specified parent, using a constructor

var o1 = {"a":3};               // create a object

var FF = function () {};        // define a function

// set the function's property key "prototype" to be the parent object you want
FF["prototype"] = o1;

// create a object, using the function as constructor
var o2 = new FF();

console.log( Object.getPrototypeOf(o2) === o1 ); // true

For detail of how this works, see JavaScript: Operator “new”.

Object and Inheritance Topic

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

  1. JavaScript: Object Object
  2. JavaScript: Object.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.