Advertisement
saasbook

Untitled

Oct 16th, 2012
1,085
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var ok_for_kids = function(movie) {
  2.   // or: function ok_for_kids(movie) { ... }
  3.   return( /^G|PG/.test(movie.rating) );
  4. }
  5. ok_for_kids; // => a function
  6. ok_for_kids({title: 'The Godfather', rating: 'R'});  // => a function call
  7.  
  8. myfunc = ok_for_kids;
  9. myfunc({title: 'The Godfather', rating: 'R'});  // => a function call
  10.  
  11.  
  12. var Movie = function(title,year,rating) {
  13.   // or:  function Movie(title,year,rating) {...}
  14.   this.title = title;
  15.   this.year = year;
  16.   this.rating = rating;
  17.   this.ok_for_kids = function() { // "instance method"
  18.     // return() must be explicit
  19.     return( /^G|PG/.test(this.rating) );
  20.   };
  21.   this.full_title = function() { // "instance method"
  22.     return(this.title + ' (' + this.year + ')');
  23.   };
  24. };
  25.  
  26. // using 'new' makes Movie the new objects prototype:
  27. var pianist = new Movie('The Pianist', 2002, 'R');
  28. var chocolat = new Movie('Chocolat', 2000, 'PG-13');
  29. pianist.full_title(); // => "The Pianist (2002)"
  30. chocolat.full_title(); // => "Chocolat (2000)"
  31. chocolat.ok_for_kids(); // => true
  32. // adding methods to an individual object:
  33. pianist.title_with_rating = function() {
  34.     return (this.title + ': ' + this.rating);
  35. }
  36. pianist.title_with_rating(); // => "The Pianist: R"
  37. chocolat.title_with_rating(); // => Error: 'undefined' not a function
  38. // but we can add functions to prototype "after the fact":
  39. Movie.prototype.title_with_rating = function() {
  40.     return (this.title + ': ' + this.rating);
  41. }
  42. chocolat.title_with_rating(); // => "Chocolat: PG-13"
  43. // we can also invoke using 'apply' -- 'this' will be bound to the
  44. //  first argument:
  45. Movie.full_title.apply(chocolat); // "Chocolat (2000)"
  46. // BAD: without 'new', 'this' is bound to global object!!
  47. juno = Movie('Juno', 2007, 'PG-13'); // DON'T DO THIS!!
  48. juno;               // undefined
  49. juno.title;         // error: 'undefined' has no properties
  50. juno.full_title();  // error: 'undefined' has no properties
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement