Posted By

brianyang on 09/01/09


Tagged


Versions (?)

creating prototypes


 / Published in: JavaScript
 

/* * Javascript's mechanism for inheritance * Allows you to add a property/method to all instances of object */

  1. // Constructor for Dog
  2. function Dog(barkNoise){
  3. // each created dog is passed in a value for their bark
  4. this.barkNoise = barkNoise;
  5. }
  6.  
  7. Dog.prototype.bark = function() {
  8. alert(this.barkNoise);
  9. };
  10.  
  11. // Each dog has 4 legs
  12. Dog.prototype.numLegs = 4;
  13.  
  14. // Here, we create a tiny dog that yaps
  15. var tinyDog = new Dog('Yap yap yap!!');
  16. var bigDog = new Dog('WOOOF!!');
  17.  
  18. // Adding properties to our Dog objects
  19. tinyDog.size = 'tiny';
  20. bigDog.size = 'big';
  21.  
  22.  
  23.  
  24. var html = '<input type="button" onclick="tinyDog.bark();" value="tinyDog.bark();">';
  25. html += '<input type="button" onclick="bigDog.bark();" value="bigDog.bark();"><br/>';
  26. html += 'tinyDog.size = ' + tinyDog.size + '<br/>';
  27. html += 'tinyDog.numLegs = ' + tinyDog.numLegs + '<br/>';
  28. html += 'bigDog.size = ' + bigDog.size + '<br/>';
  29. html += 'bigDog.numLegs = ' + bigDog.numLegs + '<br/>';
  30.  
  31. document.getElementById('content').innerHTML = html;

Report this snippet  

You need to login to post a comment.