Creare una classe in Javascript

In questo semplice tutorial vedrete come definiere una classe in Javascript.
La classe non ha una funzione speciale ma il target di questo tutorial serve a farvi "familiarizzare" con lo sviluppo delle classi con questo splendido linguaggio di programmazione.

 
// constructor:
 
function ExampleClass(p) { 
 
    if (!document.getElementById){ return; }
 
    this.elem = document.getElementById(p);
};
 
ExampleClass.prototype = {
 
    // class variables:
    elem: null,
    hoverSize: '2em',
    active: false,
 
    // functions:
    setActive: function(s) {
        this.active = s;
    },
 
    setHoverSize: function(size) {
        this.hoverSize = size;
    },
 
    getHoverSize: function(size) {
        return this.hoverSize;
    },
 
    hover: function() {
        this.style.fontSize = exampleObject.getHoverSize();
        this.style.fontWeight = 'bold';
        this.style.color = '#FFFFFF';
        this.style.backgroundColor = '#43A5E7';
    },
 
    restore: function() {
        this.style.fontSize = '1em';
        this.style.fontWeight = 'normal';
        this.style.color = '#000000'; // black
        this.style.backgroundColor = '#EFEFEF';
    },
 
    init: function() {
 
        this.setActive(true);
 
        // attach events:
        if (this.active){
            this.elem.onmouseover = this.hover;
            this.elem.onmouseout = this.restore;
        }
 
    }
}
 

Esempio

 
// init. the "ExampleClass"
var exampleObject = new ExampleClass('example');
 
// call a class function:
exampleObject.setHoverSize('1.5em');
 
// call the init function
exampleObject.init();
 
// put some text into the example div:
document.write('Fai passare il mouse qui');