Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Go to http://en.wikipedia.org/wiki/Alan_turing
- // This is function syntax. Use a function to reuse code
- // that you will use over and over again paste this into
- // the console
- function changeHeader(toName) {
- $('h1').text(toName);
- }
- // Then this
- changeHeader("George");
- // Then this
- changeHeader("Al Turing")
- // Now refresh the page to clear everything out
- // This is equivalent to the above function declaration but
- // I prefer it since it is a lot clearer what is going on
- // Which is that
- var changeHeader = function(toName) {
- $('h1').text(toName);
- };
- // changeHeader is just an object like before
- changeHeader.firstName = "George";
- changeHeader['firstName'];
- // but it has a special method
- changeHeader.call(null, "George");
- changeHeader.call(null, "Fred");
- // This can be simpler written as
- changeHeader("George");
- // You can have many parameters in a function. And since
- // an function is just an object you can pass in a function
- var ifGeorge = function(name, doThis) {
- if(name == "George") {
- doThis.call(null, name);
- }
- };
- // or with the simpler syntax:
- var ifGeorge2 = function(name, doThis) {
- if(name == "George") {
- doThis(name);
- }
- };
- // So you can call:
- ifGeorge("Fred", changeHeader); //this will do nothing
- ifGeorge("George", changeHeader); //this will change the header
- var setParagraphs = function(newText) {
- $('p').text(newText);
- };
- ifGeorge("George", setParagraphs);
- // or simply
- ifGeorge("George", function(newText){
- $('p').text(newText);
- });
Add Comment
Please, Sign In to add comment