0

I am trying to do some inheritance in JavaScript

etc

var operation = 
{
   A: 1,
   B: 2,
   C: 3
};

var operationImplA = 
{
   D: 4
};

var operationImplB = 
{
   D: function (event) {
         //do something
      }
};

Something similar to the above but not sure how to do this in JavaScript.

Jonathan
  • 2,318
  • 7
  • 25
  • 44
  • 1
    There are actually several ways to achieve this. I would suggest you read [this article](http://www.crockford.com/javascript/inheritance.html) by Douglas Crockford. See also [this question](http://stackoverflow.com/q/7486825/464709). – Frédéric Hamidi Feb 13 '13 at 15:50
  • 1
    @FrédéricHamidi: You mean that article where at the bottom he acknowledges his attempts to support a classical inheritance model were a mistake? – the system Feb 13 '13 at 16:07
  • @thesystem, absolutely, his conclusion is also valuable information IMHO. – Frédéric Hamidi Feb 13 '13 at 16:11

2 Answers2

2

You can simply use Object.create:

var operation = 
{
   A: 1,
   B: 2,
   C: 3
};

var operationImplA = Object.create(operation, {
    D: {
       value: 4
    }
});

var operationImplB = Object.create(operationImplA, {
    D: {
        value: 5
    }
});

Object.create will create new object with prototype it's first argument and properties defined in the second argument.

This is the natural prototype-based inheritance in JavaScript.

Edit

If you want to add a method, add it like a property i.e.:

var operationImplA = Object.create(operation, {
    M: {
        value: function (a) {
            console.log(a);
        }
    }
});
operationImplA.M('Some text...'); //'Some text...'
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
-1

Personally I really like John Resigs Simple JavaScript Inheritance. I use it for all my JS projects. You should try it out.

Per Salbark
  • 3,597
  • 1
  • 23
  • 24