Dark Cyber
Dark Cyber

Reputation: 2231

How to create object which inherits from a parent object?

I have this object:

var A = {
  headers: {
    'a property' : 'a value'
  }
};

How I can create another object like this?

I do not want to type the whole parent object? My new object should contain the parent object, so when I console.log var A, B, and C it should produce different results.

var B = {
  headers: {
    'a property' : 'a value',
    'b property' : 'b value'
  }
};

var C = {
  headers: {
    'a property' : 'a value',
    'b property' : 'b value'
  },
  other: {
    other2: {
      'other2 property' : 'other2 property'
    }
  }
};

Upvotes: 0

Views: 124

Answers (3)

Saeed
Saeed

Reputation: 572

You can use create function:

var B = Object.create(A);
B.headers['b property'] = 'b value';

var C = Object.create(B);
C.others = {
    other2: {
      'other2 property' : 'other2 property'
    }
  }

Upvotes: 2

Supradeep
Supradeep

Reputation: 3266

If your question is to extend the object B with the values already in A, you can use javascript object method Object.assign to do that like below :

var A = {
  headers: {
    'a property' : 'a value'
  }
};


var B = Object.assign(A);
B.headers['b property'] = 'b value';

This will copy the contents of source object i.e A.headers here into B.headers resulting below :

{
  headers: {
    'a property' : 'a value',
    'b property' : 'b value'
  }
};

Upvotes: 0

Izzet Yildirim
Izzet Yildirim

Reputation: 650

I always use Simple JavaScript Inheritance by John Resig in my projects. It is a simple yet an elegant solution for the inheritance.

By using foregoing solution you can define your classes as follows. All you need to do is extending the classes.

var Person = Class.extend({
    init: function(isDancing) {
        this.dancing = isDancing;
    }
});

var Ninja = Person.extend({
    init: function() {
        this._super(false); // => Overrides the superior constructor
    }
});

var p = new Person(true);
p.dancing; // => true

var n = new Ninja();
n.dancing; // => false

It is also helpful since there is going to be an init method for all your classes so you are going to know where to bootstrap things, and how to override things properly.

Upvotes: 0

Related Questions