jQuery: implementazione del pattern klass()

jQuery: implementazione del pattern klass()

Il pattern klass() è, nella programmazione orientata agli oggetti JavaScript, un modo per emulare i costruttori di classe di altri linguaggi orientati agli oggetti. Ad esempio, l'oggetto Class e il metodo initialize() di Prototype sono basati su questo pattern. Il metodo di inizializzazione viene invocato all'atto dell'istanziazione dell'oggetto e serve appunto a definire le sue proprietà e invocare i suoi metodi. Quindi quando si usa l'operatore new l'oggetto possiede già i suoi membri definiti. Vediamo come implemetarlo in jQuery.

Useremo una funzione globale di jQuery che chiameremo jKlass:


/** jKlass

   @author Gabriele Romanato
   @description jQuery implementation of Stoyan Stefanov's klass() function
   @requires jQuery 1.4+
   @credits Idea: http://code.google.com/p/jquery-klass/
            Inspiration and code: 'JavaScript Patterns' by Stoyan Stefanov (O'Reilly) Chapter 6, pages 128-30 **/
            
            
            
(function($) {


  $.jKlass = function(Parent, props) {
  
  
    var Child, F, i;
    
    Child = function() {
    
    
      if(Child.uber && Child.uber.hasOwnProperty('init')) {
      
        Child.uber.init.apply(this, arguments);
      
      
      }
      
      if(Child.prototype.hasOwnProperty('init')) {
      
      
        Child.prototype.init.apply(this, arguments);
      
      
      }
    
    
    
    
    };
    
    
    Parent = Parent || Object;
    
    F = function() {};
    
    F.prototype = Parent.prototype;
    
    Child.prototype = new F();
    
    Child.uber = Parent.prototype;
    
    Child.prototype.constructor = Child;
    
    for (i in props) {
    
      if(props.hasOwnProperty(i)) {
      
        Child.prototype[i] = props[i];
      
      
      }
    
    
    }
  
  
  return Child;
  
  };




})(jQuery)

Questo pattern gestisce anche l'ereditarietà tra oggetti utilizzando un pattern reso popolare da Douglas Crockford. Il metodo init() viene richiamato usando la funzione apply() che lavora sul suo array di argomenti. Esempio:


var Class = $.jKlass(null, {
  init: function() {
    this.name = 'Test';
    this.element = '<p/>';
  },
  display: function() {
  
    $('body').append(this.element).
    find('p').text(this.name);
  
  }
});

$(function() {

  var myClass = new Class();
  myClass.display();

});

Potete visionare l'esempio finale in questa pagina.

Torna su