When to use the prototype of a Function


/ Published in: JavaScript
Save to your folder(s)

Assign methods to a Function prototype when you intend to create instances of the type of object. Use object literals when you just need a container for functions.


Copy this code and paste it in your HTML
  1. // consider:
  2. function Grape(type) {
  3. this.type = type || 'Xynomavro';
  4. }
  5.  
  6. Grape.prototype.squash = function () {
  7. return this.type.substring(0, 3);
  8. };
  9.  
  10. var grape = new Grape();
  11.  
  12. alert(grape.squash());
  13.  
  14. // versus:
  15. var grapes = {
  16. barrel : [],
  17. squash : function (grape) {
  18. return grape.substring(0, 3);
  19. }
  20. };
  21.  
  22. grapes.barrel.push('Nebbiolo');
  23.  
  24. alert(grapes.squash(grapes.barrel[0]));

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.