22

Can anyone explain to me with simple words the meaning of "inheritance" in JavaScript?

6 Answers 6

57

In simple terms, inheritance is the concept of one thing gaining the properties or behaviours of something else. To say A inherits from B, is saying that A is a type of B. A Bird inherits from Animal because a Bird is a type of Animal - it can do the same things, but a little more (or differently)!

In JavaScript, this relationship is a little complicated to specify, but bear with the syntax. You must use a special object called prototype which assigns properties to a type such as Animal. Only functions have a prototype, which is why you must create a function first:

function Animal() {}; // This is the Animal *Type*
Animal.prototype.eat = function () {
    alert("All animals can eat!");
};

Now to create a type that inherits from Animal, you also use the prototype object, but this time the one belonging to the other type, e.g. Bird:

function Bird() {}; // Declaring a Bird *Type*
Bird.prototype = new Animal(); // Birds inherit from Animal
Bird.prototype.fly = function() {
    alert("Birds are special, they can fly!");
};

The effect of this is that any Birds you create (called an instance of Bird) all have the properties of Animals, but they also have the additional .fly():

var aBird = new Bird(); // Create an instance of the Bird Type
aBird.eat(); // It should alert, so the inheritance worked
aBird.fly(); // Important part of inheritance, Bird is also different to Animal

var anAnimal = new Animal(); // Let's check an instance of Animal now
anAnimal.eat(); // Alerts, no problem here
anAnimal.fly(); // Error will occur, since only Birds have fly() in its prototype
Sign up to request clarification or add additional context in comments.

1 Comment

If this is(prototype) this straight forward why people say using prototype is "controversial"?
13

A nice explanation by Robert on Inheritance in Javascript here

The way inheritance works in JavaScript is that it is prototype, instead of class-based.

For e.g

function Being () {
    this.living = true;
}
Being.prototype.breathes = function () {
    return true;  

An object which inherits Being

Robert.prototype = new Being;
function Robert () {
    this.blogs = true;
}
Robert.prototype.getsBored = function () {
    return "You betcha";
};  

So, basically, if we create a new instance of the Robert object and call some of its methods, the result would be:

// Create an instance of the Robert object
var me = new Robert();

/*
    Returns "You betcha" as it's a method
    belonging to the Robert object
*/
me.getsBored();

/*
    Returns true. Since the Robert object
    doesn't have a breathes method of
    its own, it goes back in the
    prototype chain to its parent
    object, Being, and finds the
    method there
*/
me.breathes();  

Also a good read of JavaScript inheritance : JavaScript Inheritance

Comments

1

Robert is right that "inheritance" doesn't mean anything different in JS, but it is implemented differently than in many other languages. To say that an object or class inherits from another means that members (attributes, behavior) can be defined on the parent but accessed through the child. Before you ask what "members" means, objects are aggregate types (aka composite types), and members are the components.

JS was originally designed with prototype based inheritance, where parents are objects, but class based inheritance (of a sort) can be shoehorned in by various means. Classes (and thus class inheritance) may be added to later ECMAScript standards, which is the standard that defines JS, along with other languages such as ActionScript. ActionScript already supports classes.

Closely related to "inheritance" is "extension", where a child extends a parent by adding or overriding members.

Comments

0

It's as simple that you can inherit properties from another javascript object like so:

var a = function () {}
a.prototype.sayHello = function () { alert('hello') }

var b = function () {}
b.prototype = new a();

var c = new b();
c.sayHello(); // Alerts "hello"

John Resig of jQuery has an exellent guide about it http://ejohn.org/apps/learn/ about inheritance http://ejohn.org/apps/learn/#76

EDIT Updated code based on Roberts comment.

3 Comments

Assigning a prototype from another function is a wrong way to go about inheritance in JS. After b.prototype = a.prototype you cannot add anything to the prototype of b without affecting a.
Update: see this question for details: stackoverflow.com/questions/389393/…
Shouldn't it be: b.prototype = new a();? Otherwise b is actually not inherited from a but is rather its alias/synonym.
0

The meaning of inheritance in JavaScript is no different than in any object oriented language.

Inherited children inherit their parent's behaviour (state possibilities and functionality). These children can of course add additional behaviour or override existing. In this regard inheritance in JavaScript is definitely no different than any other.

That's about the meaning in as simple words as possible. However you didn't ask how inheritance is implemented in JavaScript because that'd be a completely different story (and question). In that case we should explain differences between classes and prototypes (which are used in JavaScript).

7 Comments

I disagree with this because JavaScript is different from many other object oriented languages (intentionally). Yes, the implementation is different as well, but JavaScript uses prototypial based inheritance whereas most languages use classical inheritance.
Javascript does not have classes. Objects inherit from other objects. Though of course, you could simulate classes; but why on Earth would you want to do that?
@Dan I think this answer could do with a bit of clarification but the intent is correct... the concept of inheritance, and why it is used, does not change across languages. What's different is how it is done, and in JS that happens to be through prototypes. The term "class", while misleading to beginners, is a convenient way to describe constructor functions (and associated prototype) in JS.
You could leave the work "class" out of it and instead speak of children and parents. Using a misleading term defeats the purpose of the answer.
AFAIK: He asked for a simple explanation of inheritance in Javascript. In this particular case I think my answer was spot on. If he's not familiar with inheritance in JavaScript, he's probably also not familiar with prototype/class differences. Adding those in my answer would mean even more words which would make it complex rather than simple and also harder to understand. For someone unfamilliar to JavaScript my answer is just as good as it can get. And simple as well.
|
0

Its simple, the inheritance means: "objects/classes inherit from other objects/classes" through prototypes

for example:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";

Comments

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.