Written by davidonzo on 09/05/2008, Filled in OpenSource, Web, Tutorial
WARNING!
This article has been written 1373 days ago.
The informations may be out of dated!

JavaScript is often used to provide more contemporary routines in the same web page. This may give problem if the function, written using a regural contruction, is able to be instanced just one time.

 

To avoid this limit - is a natural limit depending by the code style used by the coder - it's necessary to build an object. This will be able to create differents instances and to use methods for any instance without create conflict with other variables and functions called by others instances.

 

Will go to define different functions inside an object constructor called using how many instances we need to create. Any instance will be able to use all the methods defined inside the object regardless from other instances.

 

To have a better idea what we are talking about, let's see an easy example where use innerHTML.

 

function showText('text', 'id'){
  this.text = text;
  this.id   = id;
 
  this.g = function(){
    return document.getElementById(this.id);
  }
 
  this.show = function(){
    this.g.innerHTML = this.text;
  }
}

first = new showText('Hello World!','myId');
first.show();

second = new showText('Hello Web!','myOtherId');
second.show();

 

The example may appear poor, but using a constructor on more complex functions, your life may be better and your coding powerful ;)

Did you find interesting this article?
Subscribe my feed to be advised of any new post!
 
.Comments rss
# 1
Ciao Davide...Sono alle prime armi con js è ho il problema di cui parli in questo post.
In particolare ho una funzione che esegue il fade tra due colori su un testo. Ha tre parametri in ingresso, un ID, e i due colori in formato esadecimale (es: 333333).

Dopo aver inizializzato tutte le variabili, attraverso setTimeout chiamo la funzione che esegue la transizione di colore vera e propria.
Potresti aiutarmi a capire come adattare queste due funzioni alla struttura del tuo esempio, di modo che posso richiamare il fade per varie righe di testo senza che mi si incasini?

Grazie
By Lck  (Sent 12/10/2009 @ 12:34:42)
# 2
Ciao..sono alle prime armi con js e ho il problema di cui parli sopra. In particolare ho due funzioni di cui una inizializza alcune variabili e chiama, con un setTimeout una seconda funzione, che cicla ricorsivamente sempre attraverso setTimeout finchè non ha raggiunto il suo obiettivo...In poche parole come faccio ad adattare la tua soluzione anche in questo caso più complesso???

Grazie
By Lck  (Sent 12/10/2009 @ 15:42:02)
# 3
Ciao Lck. E' abbastanza semplice. Basta capire che in javascript puoi definire funzioni all'interno di funzioni e dichiararle come variabili.
By davidonzo  (Sent 13/10/2009 @ 09:06:05)


Comments could be moderated.
If you don't see it immediately published, please avoid to insert it one more time.
Thanks for your patient.