Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Last active Jul 10, 2017
Embed
What would you like to do?
An example of using closures in JavaScript.
/* Closure Example 3 - Creating People For A Company*/
function Person(name, options) {
this.initialize(name, options);
}
/* Initialization function for creating a single person */
Person.prototype.initialize = function (name, options) {
this.name = name;
Object.assign(this, options);
};
/* Normal Way Optimized*/
function createPersonByJob(name, job, options) {
options.job = job;
return new Person(name, options);
}
const workersList = [];
workersList.push(
createPersonByJob('Tim', 'Programmer',{ likes: 'Pasta' }),
createPersonByJob('Jeena', 'Consultant', { hobby: 'fishing' }),
createPersonByJob('Tom', 'Programmer',{})
);
console.log(workersList);
/* Closure Way */
/* Creates a person by job with any type of property */
function createByJob(job) {
return function (name, options) {
Object.assign(options, { job: job });
return new Person(name, options);
};
}
/* ES6 Version */
createByJobES6 = (job) => (name, options) => {
Object.assign(options, { job: job });
return new Person(name, options);
};
const programmer = createByJob('Programmer');
const consultant = createByJob('Consultant');
const workerList = [
programmer('Tim', { likes: 'Pasta' }),
consultant('Jeena', { hobby: 'Fishing' }),
programmer('Tom', {})
];
console.log(workerList);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment