views:

132

answers:

3

Possible Duplicate:
Performing Inheritance in Javascript

What are the ways to implement inheritance in JavaScript Which one is the best and why?

+3  A: 

I can think of only one: prototyping, with which you can do polymorphism, a bit of encapsulation and inheritance. That's the only way inheritance* is supported by JavaScript, but quite successfully and to quite a deep extend. See this nice and easy read on OO in JavaScript.

An excellent read, too, is Object Oriented JavaScript by Stoyan Stefanov, I can highly recommend it to you, your JS will never look the same again.

* EDIT: this is a special type of OO: prototype based programming, and JS supports it well, but as commented by Adam, you can trick your way through if you want to do it differently (advice: don't).

Abel
There are other methods, but they are just trickery that attempts to hide JS's true prototypal inheritence. It's best not to fight JS. Playing by its rules can be uncomfortable for those who are used to C++/C#/Java-like inheritance schemes, but not embracing JS for what it is would probably be a mistake.
Adam Crossland
+1 Adam, I agree, esp. with "don't fight JS". I encorporated your comment in my answer, hope you don't mind.
Abel
+1  A: 

Doug Crockford lists several mechanisms for inheritance in his "Javascript: The Good Parts". I'd recommend reading that for a deep understanding. The material might also be available on line.

duffymo
His discussion of inheritance is one of the better parts of The Good Parts. Generally an excellent book, but you can't just take the whole thing at face-value.
Adam Crossland
A: 

Since JavaScript is a class-free, object-oriented language, it uses prototypal inheritance. Read Douglas Crockford's "Prototypal Inheritance in JavaScript" to learn why: http://javascript.crockford.com/prototypal.html

phreeskier
Guess you missed duffymo's answer here, which says the same: http://stackoverflow.com/questions/3320185/how-to-implement-or-use-inheritance-in-javascript/3320218#3320218 ;-)
Abel