Last active
August 29, 2015 14:04
-
-
Save GaProgMan/adf72fca160736fb8d14 to your computer and use it in GitHub Desktop.
A scratch-pad (playground) for javascript stuff, as I learn it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Invoking functions via parameters to other functions */ | |
var work = function() { | |
console.log("this is being invoked"); | |
}; | |
var doWork = function(f) { | |
console.log("invoking work"); | |
try { | |
f(); | |
} catch (ex) { | |
console.log(ex); | |
} | |
console.log("work has been invoked"); | |
}; | |
doWork(work); | |
/* Encapsulation module pattern */ | |
var program = function() { | |
/* Revealing module pattern */ | |
var createWorker = function() { | |
// workCount will not be exposed to the user, directly | |
var workCount = 0; | |
// Create tasks | |
var task1 = function() { | |
workCount += 1; | |
console.log("task1 " + workCount); | |
}; | |
var task2 = function() { | |
workCount += 1; | |
console.log("task2 " + workCount); | |
}; | |
// return tasks as "job1" and "job2" | |
// applying aliases on the vars | |
return { | |
job1: task1, | |
job2: task2 | |
}; | |
}; | |
var worker = createWorker(); | |
worker.job1(); | |
worker.job2(); | |
worker.job2(); | |
}; | |
// can be invoked as IIFE - Immediately invoked function expression - by adding | |
// () in place of the final semi-colon, wrapping in brackets, and dropping | |
// "var program = " | |
program(); | |
/* IIFE pattern of previous method */ | |
(function() { | |
// IIFE is used as JavaScript interpreters don't "like" annonymous | |
// method calls (I.E | |
// function (someData) { ... }; | |
/* Revealing module pattern */ | |
var createWorker = function() { | |
// workCount will not be exposed to the user, directly | |
var workCount = 0; | |
// Create tasks | |
var task1 = function() { | |
workCount += 1; | |
console.log("task1 " + workCount); | |
}; | |
var task2 = function() { | |
workCount += 1; | |
console.log("task2 " + workCount); | |
}; | |
// return tasks as "job1" and "job2" | |
// applying aliases on the vars | |
return { | |
job1: task1, | |
job2: task2 | |
}; | |
}; | |
var worker = createWorker(); | |
worker.job1(); | |
worker.job2(); | |
worker.job2(); | |
}()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment