1

I have searched for a way of defining a class in javascript like in java or php but I found none!

I want something like

class javascriptClass {

       function someFunction(){}

}
Ry-
  • 218,210
  • 55
  • 464
  • 476
Gpak
  • 3,342
  • 2
  • 21
  • 19
  • 1
    http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript – bobince May 05 '12 at 20:54

3 Answers3

5

You can use a prototype class, like so:

function MyClass() {

}

MyClass.prototype.method1 = function() {
    // do stuff
};

MyClass.prototype.method2 = function(p) {
    // do stuff
};

var myClass = new MyClass();

Now, after instantiating an object myClass from the prototype MyClass, you can access the methods of the object myClass:

myClass.method1();

The above method is great if you need to instantiate more than one object/instance of the class.

If you only expect to have one object, then another method you can use simply acts as a namespace to protect your functions from collisions with others:

var myObject = {

    method1: function() {
        // do stuff
    },

    method2: function(p) {
        // do stuff
    }
};

myObject.method1();
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
2

In JavaScript, you don't have classes as such. You define functions that are used to create objects with new, and you can give them methods by either creating them in the body of the constructor, or adding them through the object's prototype. For example:

function JavaScriptClass() {
    // I am a JavaScript constructor! Any initialization can be done here.
}

// This is the prototype! You can put instance methods and variables (to an extent) here.
JavaScriptClass.prototype.someFunction = function() {
    alert('someFunction was called!');
};

// Now, let's create an instance!
var obj = new JavaScriptClass();
obj.someFunction(); // someFunction was called!

And you can access the current object using this, in both the constructor and any methods bound to the object. Note that this can also be bound to just about anything in JavaScript. It's a different type of OOP.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • And how do I extend that class? – Gpak May 05 '12 at 21:05
  • 1
    @user899566: Using the `prototype` object. Set the `prototype` of the child class to an instance of the parent class. (Google: "prototypal inheritance") – Ry- May 05 '12 at 21:07
2

Unlike class-based languages, JavaScript is functional languages or prototypal language, you can't use class keyword or the kind of signature you have posted in JavaScript. In JavaScript, normally you would do:

function Person(){
  // public members
  this.foo = 'foo';
  this.walk = function(){ ......... }

  // private members
  var bar = 'bar';
  var baz = function(){.........}
}

var person = new Person();
Sarfraz
  • 377,238
  • 77
  • 533
  • 578