Skip to content

Instantly share code, notes, and snippets.

@marlun78
Last active August 29, 2015 13:57
Show Gist options
  • Save marlun78/9387694 to your computer and use it in GitHub Desktop.
Save marlun78/9387694 to your computer and use it in GitHub Desktop.
Self-overwriting function statement - an alternative to IIFE?
/**
* Self-overwriting Function Statement (SOFS)
* Copyright (c) 2013, marlun78
* MIT License, https://gist.github.com/marlun78/bd0800cf5e8053ba9f83
*
* === EXAMPLE ===
* console.log('---');
* console.log('SOFS return:', sofs());
* console.log('SOFS return:', sofs());
* console.log('---');
* console.log('IIFE return:', iife());
* console.log('IIFE return:', iife());
* console.log('---');
*
* === OUTPUTS ===
* IIFE context created
* ---
* SOFS context created
* SOFS call
* SOFS return: 1
* SOFS call
* SOFS return: 2
* ---
* IIFE call
* IIFE return: 1
* IIFE call
* IIFE return: 2
* ---
*/
(function () {
'use strict';
/**
* IIFE (immediately-invoked function expression)
*
* + ’Standard’ and pretty easy to understand
* - Its an expression, location dependent, not usable throughout the whole scope (well depends on where it is)
* - Execution context is created immediately
* + Name repetition count 2
* - 3 bytes heavier (in its shortest variant, min 45 chars)
*
*/
var iife = (function () {
//Private
var times = 0;
console.log('IIFE context created');
//The actual function with access to the private stuff
return function iife() {
console.log('IIFE call');
return ++times;
};
}());
/**
* SOFS (self-overwriting function statement)
*
* - Not ’standard’ and looks a bit complicated
* + Its a statement - location independent, usable throughout the whole scope
* + Lazy - execution context creation deferred until first use
* - Name repetition count 4
* + 3 bytes lighter (in its shortest variant, min 42 chars)
*
*/
function sofs() {
//Private
var times = 0;
console.log('SOFS context created');
//The actual function with access to the private stuff
sofs = function sofs() {
console.log('SOFS call');
return ++times;
};
//Remember to invoke the new function on first call!
//return sofs.apply(this, arguments);
return sofs();
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment