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.

3
  • 1
    There are actually several ways to achieve this. I would suggest you read this article by Douglas Crockford. See also this question. Commented Feb 13, 2013 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? Commented Feb 13, 2013 at 16:07
  • @thesystem, absolutely, his conclusion is also valuable information IMHO. Commented Feb 13, 2013 at 16:11

2 Answers 2

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

2 Comments

if I wanted to add a function etc function AA(A, B) {}; How would I do this? In the inherited obj. Tnks!!
Just like a usual property: func: { value: function () {} }
-1

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

1 Comment

I don't think the OP wants to create a class. He just wants one object to inherit from another.

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.