Created
November 28, 2014 11:15
-
-
Save kkoziarski/2b971b86466314f58c96 to your computer and use it in GitHub Desktop.
new object - The Good Parts
This file contains 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
var mammal = function (spec) { | |
var that = {}; | |
that.get_name = function ( ) { | |
return spec.name; | |
}; | |
that.says = function ( ) { | |
return spec.saying || ''; | |
}; | |
return that; | |
}; | |
var myMammal = mammal({name: 'Herb'}); | |
function Person() { | |
var privateProperty = "123"; | |
this.name = "John"; | |
return this; | |
} | |
var person = new Person(); | |
////////////////TYPESCRIPT | |
var Greeter = (function () { | |
function Greeter(message) { | |
this.greeting = message; | |
} | |
Greeter.prototype.greet = function () { | |
return "Hello, " + this.greeting; | |
}; | |
return Greeter; | |
})(); | |
var greeter = new Greeter("world"); | |
/////////////////////////////////////////////////////// | |
//Self-Executing Anonymous Func: Part 2 (Public & Private) | |
(function( MYAPP, $, undefined ) { | |
//Private Property | |
var isHot = true; | |
//Public Property | |
MYAPP.ingredient = "Bacon Strips"; | |
//Public Method | |
MYAPP.fry = function() { | |
var oliveOil; | |
addItem( "\t\n Butter \n\t" ); | |
addItem( oliveOil ); | |
console.log( "Frying " + MYAPP.ingredient ); | |
}; | |
//Private Method | |
function addItem( item ) { | |
if ( item !== undefined ) { | |
console.log( "Adding " + $.trim(item) ); | |
} | |
} | |
}( window.MYAPP = window.MYAPP || {}, jQuery )); //function is immediately called with arguments | |
//What is window.MYAPP = window.MYAPP || {} doing? | |
//The code checks to see if MYAPP exists in the global namespace (window). | |
//If it does not exist, then window.MYAPP is assigned an empty object literal. | |
//Public Properties | |
console.log( MYAPP.ingredient ); //Bacon Strips | |
//Public Methods | |
MYAPP.fry(); //Adding Butter & Fraying Bacon Strips | |
//Adding a Public Property | |
MYAPP.quantity = "12"; | |
console.log( MYAPP.quantity ); //12 | |
//Adding New Functionality to the MYAPP | |
(function( MYAPP, $, undefined ) { | |
//Private Property | |
var amountOfGrease = "1 Cup"; | |
//Public Method | |
MYAPP.toString = function() { | |
console.log( MYAPP.quantity + " " + | |
MYAPP.ingredient + " & " + | |
amountOfGrease + " of Grease" ); | |
console.log( isHot ? "Hot" : "Cold" ); | |
}; | |
}( window.MYAPP = window.MYAPP || {}, jQuery )); | |
try { | |
//12 Bacon Strips & 1 Cup of Grease | |
MYAPP.toString(); //Throws Exception | |
} catch( e ) { | |
console.log( e.message ); //isHot is not defined | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment