How do you write a class in javascript?

Possible duplicate:
What is the best way to define a class in javascript

How do you write a class in javascript? Is it possible?

+7
javascript class
source share
6 answers

Well, JavaScript is a prototype-based language, it has no classes, but you can have classic inheritance and other behavior reuse patterns by cloning objects and prototyping.

Featured Articles:

+7
source share
function Foo() { // constructor } Foo.prototype.bar = function() { // bar function within foo } 
+3
source share

Javascript uses the prototype OO by default.

However, if you use a prototype library, for example, you can use Class.create ().

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

This will allow you to create (or inherit) a class, after which you will create instances with new ones.

Other libraries probably have similar capabilities.

+2
source share

If you use a library such as a prototype or jQuery, this is much simpler, but the legacy way is to do this.

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

Here you can read here http://www.komodomedia.com/blog/2008/09/javascript-classes-for-n00bs/

+1
source share

This "kind of" is possible. Prototype has built-in help when writing classes in JS. Take a look at this detailed description of how you can do this.

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

JavaScript is based on objects, not classes. It uses prototype inheritance, not classic inheritance.

JavaScript is flexible and easily extensible. As a result, there are many libraries that add classic JavaScript inheritance. However, using them, you run the risk of writing code that is difficult for most JavaScript programmers to execute.

0
source share

All Articles