-
Write a function,
nonsense
that takes an inputstring
. This function contains another function,blab
which alertsstring
and is immediately called inside the functionnonsense
.blab
should look like this inside of thenonsense
function:var blab = function(){ alert(string); };
-
In your function,
nonsense
, change the immediate call to a setTimeout so that the call toblab
comes after 2 seconds. Theblab
function itself should stay the same as before. -
Now, instead of calling
blab
inside ofnonsense
, returnblab
(without invoking it). Callnonsense
with some string and store the returned value (theblab
function) in a variable calledblabLater
. Callnonsense
again with a different string and store the returned value in a variable calledblabAgainLater
. -
Inspect
blabLater
andblabAgainLater
in your console. Call them (they are functions!) and see what happens! -
Write a function with a closure. The first function should only take one argument, someone's first name, and the inner function should take one more argument, someone's last name. The inner function should console.log both the first name and the last name.
var lastNameTrier = function(firstName){ //does stuff var innerFunction = function() { //does stuff }; //maybe returns something here }; var firstNameFarmer = lastNameTrier('Farmer'); //logs nothing firstNameFarmer('Brown'); //logs 'Farmer Brown'
This function is useful in case you want to try on different last names. For example, I could use firstName again with another last name:
firstNameFarmer('Jane'); //logs 'Farmer Jane' firstNameFarmer('Lynne'); //logs 'Farmer Lynne'
-
Create a
storyWriter
function that returns an object with two methods. One method,addWords
adds a word to your story and returns the story while the other one,erase
, resets the story back to an empty string. Here is an implementation:var farmLoveStory = storyWriter(); farmLoveStory.addWords('There was once a lonely cow.'); // 'There was once a lonely cow.' farmLoveStory.addWords('It saw a friendly face.'); //'There was once a lonely cow. It saw a friendly face.' var storyOfMyLife = storyWriter(); storyOfMyLife.addWords('My code broke.'); // 'My code broke.' storyOfMyLife.addWords('I ate some ice cream.'); //'My code broke. I ate some ice cream.' storyOfMyLife.erase(); // ''
henimezrani / closures Goto Github PK
View Code? Open in Web Editor NEWThis project forked from abdlrrahman/closures