Receive our weekly advanced programming tips for FREE
29.June
How to create classes in JavaScript
0
| 0 votes
Autor: bookkeeper
Chapter: JavaScript
Tags:
js

There is three ways to create classes in JavaScript.

1. Define methods internally

function MyClass (parameter){
    this.something = parameter;
    this.getParameter = function() {
        return this.something;
    };
}

var my_class = new MyClass('Something');
alert(my_class.something);
my_class.getParameter();

2. Using JSON

var MyClass = {
    something: "parameter",
    getParameter: function() {
        return this.something;
    }
}

alert(MyClass.something);
alert(MyClass.getParameter());

3. Singleton using a function

var MyClass = new function() {
    this.something = "parameter";
    this.getParameter = function() {
        return this.something;
    };
}

alert(MyClass.something);
alert(MyClass.getParameter());

Use which ever is better for you.