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?

Community
  • 1
  • 1

6 Answers6

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:

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
3
function Foo() {
   // constructor
}

Foo.prototype.bar = function() {
    // bar function within foo
}
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
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.

alamar
  • 18,729
  • 4
  • 64
  • 97
  • Some do. jQuery doesn't, as it expects that you'll be more likely to deal with jQuery collections than with classes. – Nosredna May 29 '09 at 19:18
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/

NerdyNick
  • 813
  • 1
  • 9
  • 17
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');
AgileJon
  • 53,070
  • 5
  • 41
  • 38
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.

Nosredna
  • 83,000
  • 15
  • 95
  • 122