Skip to content

Instantly share code, notes, and snippets.

@elijahmanor
Last active December 13, 2015 23:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elijahmanor/4991287 to your computer and use it in GitHub Desktop.
Save elijahmanor/4991287 to your computer and use it in GitHub Desktop.
Angry Birds of JavaScript Development: Red Bird
// JavaScript can parse this just fine now, yay!
(function() {
// All memory is contained within this scope
}()); // <-- Immediately Invoked
var type = "Red",
attack = function() {
typeOfBird = type + " Bird";
window.message = typeOfBird + " Attacks!";
return typeOfBird + " Bird Attacks!";
};
console.log( window.type ); // I'm a global variable
console.log( window.attack() ); // I'm a global function
console.log( window.typeOfBird ); // I'm a global variable too :(
console.log( window.message ); // I'm a global variable too :|
var type = "Red",
attack = function() {
console.log( type + " Bird Attacks!" );
};
console.log( window.type ); // I'm a global variable
console.log( window.attack ); // I'm a global function
var type = "Red",
attack = function() {
typeOfBird = type + " Bird";
return typeOfBird + " Bird Attacks!";
};
console.log( window.type ); // I'm a global variable
console.log( window.attack() ); // I'm a global function
console.log( window.typeOfBird ); // I'm a global variable too :(
// Gather type & attack and make properties off higher level object
var bird = {
type: "Red",
attack: function() {
console.log( this.type + " Bird Attacks!" );
}
};
console.log( window.bird ); // Only 1 global object!
console.log( window.bird.type ); // Red
console.log( window.bird.attack() ); // Red Bird Attacks!
(function( bird ) {
var power = "IIFE"; // This is private
bird.type = "Red";
bird.attack = function() {
console.log( bird.type + " Bird Attacks with an " + power + "!" );
};
}( window.bird = window.bird || {} ));
console.log( window.bird ); // Only 1 global object!
console.log( window.bird.type ); // Public property
console.log( window.bird.attack() ); // Public method accessing private var
console.log( window.bird.power ); // Private variable, can't access
// Revealing Module Pattern
var bird = (function() {
var type = "Red",
power = "IIFE", // This is private
attack = function() {
console.log( type + " Bird Attacks with an " + power + "!" );
};
return { // Only the items returned are public
type: type,
attack: attack
};
}());
console.log( window.bird ); // Only 1 global object!
console.log( window.bird.type ); // Public property
console.log( window.bird.attack() ); // Public method accessing private var
console.log( window.bird.power ); // Private variable, can't access
// Error: JavaScript can't parse this correctly
function() {
// All memory is contained within this scope
}(); // <-- Immediately Invoked
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment