togakangaroo

Learn Js Nola - Functions

Apr 18th, 2012
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Go to http://en.wikipedia.org/wiki/Alan_turing
  2.  
  3. // This is function syntax. Use a function to reuse code
  4. // that you will use over and over again  paste this into
  5. // the console
  6. function changeHeader(toName) {
  7.     $('h1').text(toName);
  8. }
  9.  
  10. // Then this
  11. changeHeader("George");
  12.  
  13. // Then this
  14. changeHeader("Al Turing")
  15.  
  16.  
  17. // Now refresh the page to clear everything out
  18.  
  19. // This is equivalent to the above function declaration but
  20. // I prefer it since it is a lot clearer what is going on
  21. // Which is that
  22. var changeHeader = function(toName) {
  23.     $('h1').text(toName);
  24. };
  25. // changeHeader is just an object like before
  26. changeHeader.firstName = "George";
  27. changeHeader['firstName'];
  28. // but it has a special method
  29. changeHeader.call(null, "George");
  30. changeHeader.call(null, "Fred");
  31. // This can be simpler written as
  32. changeHeader("George");
  33.  
  34. // You can have many parameters in a function. And since
  35. // an function is just an object you can pass in a function
  36. var ifGeorge = function(name, doThis) {
  37.    if(name == "George") {
  38.       doThis.call(null, name);
  39.    }
  40. };
  41. // or with the simpler syntax:
  42. var ifGeorge2 = function(name, doThis) {
  43.    if(name == "George") {
  44.       doThis(name);
  45.    }
  46. };
  47.  
  48. // So you can call:
  49. ifGeorge("Fred", changeHeader); //this will do nothing
  50. ifGeorge("George", changeHeader); //this will change the header
  51. var setParagraphs = function(newText) {
  52.     $('p').text(newText);
  53. };
  54. ifGeorge("George", setParagraphs);
  55. // or simply
  56. ifGeorge("George", function(newText){
  57.     $('p').text(newText);
  58. });
Add Comment
Please, Sign In to add comment