1. Object Oriented JavaScript
JavaScript is a flexible Embrace the principles of
and expressive language OO design and how
that should be written prototypical languages like
clearly and concisely. JavaScript fit into this
paradigm.
JavaScript is one of the
cornerstones to the
powerful set of tools
made available by
HTML5
2. Remember Why?
Just to name some of the reasons...
Encapsulation
Composition
Inheritance
Polymorphism
3. Prototype Based Language
No formal class defn.
Objects are prototypes
Inheritance through
cloning
ex nihilo "from nothing"
6. Inheritance
CrabBisque = function() {};
//Lets inherit from the BaseSoup object from the previous slides
CrabBisque.prototype = new BaseSoup;
CrabBisque.prototype.constructor = CrabBisque;
CrabBisque.prototype.parent = BaseSoup.prototype;
CrabBisque.prototype.description = function() {
return "Delicious crab in a rich cream broth";
}
var bisque = new CrabBisque();
bisque.menuDisplay();
9. call ~ super
CrabBisque = function() {
BaseSoup.call(this); //call the super object constructor
name = "Crab Bisque";
ingredients = ["salt", "mirepoix",
"heavy cream", "crab", "butter"
"leeks", "pepper", "tomato paste"];
};
CrabBisque.prototype.description = function() {
return BaseSoup.prototype.description.call(this); //call the super method
}
10. "From Nothing"
var lunch = {soup: new Jambalaya(), bread: true,
drink: "Coke", burp: function() { return "yum"}};
11. Static Objects
SoupFactory = (function() {
return {
serve: function(person) {
switch(person.name()) {
case "Newman":
return new Jambalaya();
case "George":
return new CrabBisque();
case "Elaine":
return new Mulligatawny();
default:
return new LimaBean();
}
}
}
})();
12. Closures / Anonymous Functions
//function in a function
//retains a copy of the local variable despite being an anon function
FatCat = function() {
var weight = 4;
this.eat = function() { weight++; };
this.weighIn = function() { alert(weight); };
this.speak = function() {
kittyTalk = function() { alert(meow); }
//NOTE: meow is defined _after_ the anon above...it still works!
var meow = "Meeeooww";
return kittyTalk; //just got functional
}
}
13. Functional Sprinkles of Goodness
function each(arrayOfStuff, action) {
for(var i = 0; i < arrayOfStuff.length; i++) {
action(arrayOfStuff[i]);
}
}
each([1,2,3,4,5], alert);