7

Possible Duplicate:
What's the best way to define a class in javascript

How do you write a class in Javascript? Is it even possible?

2
  • Ack. "javascript" got edited to "Javascript" rather than "JavaScript." Commented May 29, 2009 at 19:20
  • 3
    I prefer jAvAsCrIpt. It is the correct way. Commented May 30, 2009 at 3:51

6 Answers 6

7

Well, JavaScript is a Prototype-Based language, it does not have classes, but you can have classical inheritance, and other behavior reuse patterns through object cloning and prototyping.

Recommended articles:

Sign up to request clarification or add additional context in comments.

Comments

3
function Foo() { // constructor } Foo.prototype.bar = function() { // bar function within foo } 

3 Comments

I think you have an extra "function" at the beginning of bar. :-)
Yeah. Also, don't forget to mention that you have to use new Foo().
whoops fixed, im so not used to writing javascript oo.
2

Javascript uses prototype-based OO by default.

However, if you're using prototype library, for example, you can use Class.create().

http://prototypejs.org/api/class/create

It would let you to create (or inherit) a class, after that you would instantiate its instances with new.

Other libraries probably have similar facilities.

1 Comment

Some do. jQuery doesn't, as it expects that you'll be more likely to deal with jQuery collections than with classes.
1

If you use a library like prototype or jQuery its a lot easier but the legacy way is to do this.

function MyClass(){ } MyClass.prototype.aFunction(){ } var instance = new MyClass(); instance.aFunction(); 

You can read more on it here http://www.komodomedia.com/blog/2008/09/javascript-classes-for-n00bs/

Comments

0

It's "sort of" possible. Prototype has some built-in help with writing classes in JS. Take a look at this thorough description of how you can do it.

var namedClass = Class.create({ initialize: function(name) { this.name = name; } getName: function() { return this.name; } }); var instance = new namedClass('Foobar'); 

Comments

0

JavaScript is based on objects, not classes. It uses prototypal inheritance, not classical inheritance.

JavaScript is malleable and easily extensible. As a result, there are many libraries that add classical inhertance to JavaScript. However, by using them you risk writing code that's difficult for most JavaScript programmers to follow.

Comments