views:

527

answers:

6

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  A: 

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.

alamar
Some do. jQuery doesn't, as it expects that you'll be more likely to deal with jQuery collections than with classes.
Nosredna
+2  A: 
function Foo() {
   // constructor
}

Foo.prototype.bar = new function() {
    // bar function within foo
}
Ólafur Waage
I think you have an extra "function" at the beginning of `bar`. :-)
Ben Blank
Yeah.Also, don't forget to mention that you have to use new Foo().
alamar
whoops fixed, im so not used to writing javascript oo.
Ólafur Waage
A: 

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');
AgileJon
A: 

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.

Nosredna
A: 

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/

NerdyNick
+2  A: 

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:

CMS