Last active
August 29, 2015 14:01
-
-
Save adamghill/45e71bb6ce130fba86af to your computer and use it in GitHub Desktop.
JavaScript examples
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
// http://jsfiddle.net/D8VQs/ | |
function print(str, obj) { | |
console.log(str, obj); | |
// Use jQuery if it's available | |
if (typeof($) != 'undefined') { | |
var $output = $('#output'); | |
if ($output) { | |
if (str && obj) { | |
$output.append('<li>' + str + ': ' + obj + '</li>'); | |
} else { | |
$output.append('<li></li>'); | |
} | |
} | |
} | |
} | |
function newLine() { | |
print('', ''); | |
} | |
// Function/variable scope | |
/**/ | |
var scope = function() { | |
var currentScope = ''; | |
// Self-executing function | |
(function() { | |
currentScope = 'outermost'; | |
print('currentScope', currentScope); | |
var x = 1; | |
print('x', x); | |
newLine(); | |
// Function as a variable that gets executed via outerScope() | |
var outerScope = function() { | |
currentScope = 'outer'; | |
print('currentScope', currentScope); | |
var y = 2; | |
print('x', x); | |
print('y', y); | |
// Hoisting: http://code.tutsplus.com/tutorials/javascript-hoisting-explained--net-15092 | |
var x = 1; | |
try { | |
print('t', t); | |
} catch(ex) { | |
print('Exception', ex); | |
} | |
try { | |
print('z', z); | |
} catch(ex) { | |
print('Exception', ex); | |
} | |
newLine(); | |
// Implicit function that gets executed via innerScope() | |
function innerScope(z) { | |
currentScope = 'inner'; | |
print('currentScope', currentScope); | |
var t = 0; | |
print('x', x); | |
print('y', y); | |
print('z', z); | |
} | |
innerScope(3); | |
} | |
outerScope(); | |
})(); | |
} | |
scope(); | |
newLine(); | |
/**/ | |
// Binding scope | |
// Blatently ripped off from http://www.reactive.io/tips/2009/04/28/binding-scope-in-javascript/ | |
/**/ | |
name = "window"; | |
object = { | |
name: "object", | |
action: function(greeting) { | |
nestedAction = function(nestedGreeting) { | |
console.log(nestedGreeting + " " + this.name); | |
}//.bind(this); // #3 | |
nestedAction(greeting); | |
// nestedAction.call(this, greeting); // #1 | |
// nestedAction.apply(this, [greeting]); // #2 | |
} | |
} | |
object.action("hello"); | |
/**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment