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?
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?
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.
function Foo() {
// constructor
}
Foo.prototype.bar = new function() {
// bar function within foo
}
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');
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.
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/
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: