The Tricky.net

JavaScript


The this keyword
If you go a bit further with javascript, you would certainly meet the famous keyword this, and certainly notice that it is the source of many of your problems if you play with classes and events.
Let's see an example:

 
var Family = function(){
 this.nbPersons = 0;
 window.onclick = this.addMember;                
}
 
Family.prototype.addMember = function(){
 this.nbPersons++;    
 document.body.innerHTML += 'New family member added! nbPerson is ' + this.nbPersons + '!<br/>';
}
 
var myFamily = new Family();
 

So we built a super basic class, called Family, which is also the constructor: the class function addMember is then registered as click event listener to the window object. The addMember function just increment the number of person in the family.
The class is then instanciated with the new keyword.
Read more...
 
<< Start < Prev 1 2 Next > End >>

Page 2 of 2