Advertisement
saasbook

prototype_example.js

Jan 9th, 2013
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. var Movie = function(title,year,rating) {
  2. this.title = title;
  3. this.year = year;
  4. this.rating = rating;
  5. this.full_title = function() { // "instance method"
  6. return(this.title + ' (' + this.year + ')');
  7. };
  8. };
  9. // using 'new' makes Movie the new objects' prototype:
  10. pianist = new Movie('The Pianist', 2002, 'R');
  11. chocolat = new Movie('Chocolat', 2000, 'PG-13');
  12. pianist.full_title(); // => "The Pianist (2002)"
  13. chocolat.full_title(); // => "Chocolat (2000)"
  14. // adding methods to an individual object:
  15. pianist.title_with_rating = function() {
  16. return (this.title + ': ' + this.rating);
  17. }
  18. pianist.title_with_rating(); // => "The Pianist: R"
  19. chocolat.title_with_rating(); // => Error: 'undefined' not a function
  20. // but we can add functions to prototype "after the fact":
  21. Movie.prototype.title_with_rating = function() {
  22. return (this.title + ': ' + this.rating);
  23. }
  24. chocolat.title_with_rating(); // => "Chocolat: PG-13"
  25. // we can also invoke using 'apply' -- 'this' will be bound to the
  26. // first argument:
  27. Movie.full_title.apply(chocolat); // "Chocolat (2000)"
  28. // BAD: without 'new', 'this' is bound to global object in Movie call!!
  29. juno = Movie('Juno', 2007, 'PG-13'); // DON'T DO THIS!!
  30. juno; // undefined
  31. juno.title; // error: 'undefined' has no properties
  32. juno.full_title(); // error: 'undefined' has no properties
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement