Written by davidonzo on 09/05/2008, Filled in OpenSource, Web, Tutorial

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

No comments yet...



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