Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
JavaScript
From birth to closure
Yeah, nothing
Brendan Eich
Brendan Eich
What is JavaScript?
• Developed by Brendan Eich 1995
• Initially called Mocha, then LiveScript
• First day of light in a beta of Netscape 2
  ...
“You’re number one!”
Has NOTHING to do
     with Java!
• JavaScript is one of the world’s most
  popular programming languages
• One interpreter on every machine
• ECMAScript st...
SunSpider test
Douglas Crockford
Douglas Crockford
• JSON
• JSLint
• JSMin
JavaScript basics
Variable declaration:
var benAffleck = ”Actor”;
Function declaration:
function benQuote () {
! return "Rumors about me?
    Calista Flockhart, Pam
    Anderson, and Matt ...
Conditionals
• If
• Switch
• Shorthand assignment
• Ternary operators
function makeMovie (withLivTyler) {
! var nice = withLivTyler || false;
}
(datedJLo)? "Lucky guy!" : "No?";
Comparison operators
• =	

 Assignment
• ==	

 Equality
• === Identity
// Assignment
var bestFriend = "Matt Damon";

// Equality
if (5 == "5") {
 ! // true
}

// Identity
if (5 === "5") {
 ! //...
// Short-circuit logic
if (true || false)

if (false && true)

// Makes this code safe
if (obj && obj.property)
// Short-circuit logic
if (true || false)

if (false && true)

// Makes this code safe
if (obj && obj.property)
Type coercion
// true
5 == "5"

// 123
"1" + 2 + 3;
// 6, manual type conversion
parseInt("1", 10) + 2 + 3;
null == undefined == 0 ==
    false == ""


•   Not really, but sort of
•   Rather “truthy” or “falsy”
var    a = null;
var    b; // undefined
var    c = 0;
var    d = false;
var    e = "";

if    (a)   //   false
if    (b)  ...
JavaScript data types
• string
• number
• boolean
• null
• undefined
• Object
Types of Object include:

• function
• Array
• Date
• RegExp
Checking type
typeof return values:

• string
• number
• boolean
• function
• object
• undefined
typeof fanClub // "undefined"


var title = "Armageddon";
typeof title // Equals "string"


var age = 37;
typeof age // Eq...
function anotherQuote () {
! return "If I ever woke up
   with a dead hooker in my
   hotel room, Matt would be
   the fir...
var obj = {};
typeof obj = // "object"


var arr = ["B", "E", "N"];
typeof arr // "object"
var obj = {};
typeof obj = // "object"


var arr = ["B", "E", "N"];
typeof arr // "object"     ?!
Using instanceof
obj instanceof Array // false
arr instanceof Array // true
Functions
Procedural


function notAHit () {
! return "Gigli";
}
Functions as variables

var wroteScript = function () {
! return "Good Will Hunting";
};
wroteScript();
Anonymous


document.onmousemove = function (evt) {
   alert(evt.pageX);
};
Self-invoking


(function () {
! var dogma = "Shot in 1999";
})();
Self-invoking


(function () {
! var dogma = "Shot in 1999";
})();
Function arguments
• Any argument can be omitted
• Any argument can be added
• No overloading
• The arguments collection
function concat (a, b, c) {
! return a + b + c;
}

concat(1, 2, 3); // 6
concat(1, 2); // NaN
• The arguments collection
• Property: arguments.length
• NOT an array
function concat () {
! var sum = 0,
      l = arguments.length;
! for (var i=0; i<l; i++) {
! ! sum += arguments[i];
! }
!...
Objects
Object constructor
function Ben () {
! this.name = "Ben Affleck";
! this.gotAnOscar = true;
};

var ben = new Ben();
alert...
Object literal

var ben = {
! name : "Ben Affleck",
! gotAnOscar : true
};

alert(ben.name); // "Ben Affleck"
Different syntax, same thing:
ben["arms"] = 2;
ben.arms = 2;
Different syntax, same thing:
ben["arms"] = 2;
ben.arms = 2;
For any object:
var ben = {};
ben[1972] = "Year of birth";
ben["born"] = 1972;
ben[true] = false;
var regEx = new RegExp;
regEx[3] = "I can do this?";
var goodMovie = {
! title : "Good Will Hunting",
! year : 1997
};

for (var item in goodMovie) {
! alert(item + ": " + goo...
var goodMovie = {
! title : "Good Will Hunting",
! year : 1997
};

// Check returns true
if ("year" in goodMovie) {
! aler...
Inheritance
• Prototype-based inheritance
• Not class-based
• The prototype chain checks itself first
• It then goes to the parent, parent’s parent
  etc...
function Being () {
! this.living = true;
}

Being.prototype.greet = function () {
! return "Hello!";
};
function Ben () {
! this.talks = true;
}
Ben.prototype = new Being;


Ben.prototype.saySomething = function () {
 ! return...
// Create an instance
var ben = new Ben();


// Returns "I feel like fame is wasted on me."
ben.saySomething();


// Retur...
Checking for the greet() method in this order:

• ben instance
• Ben prototype
• Being prototype
• Object prototype
Class-based mimicking

• Simple JavaScript Inheritance
• A Base Class for JavaScript Inheritance
• Defining classes and inh...
Why prototype syntax

• It’s native, i.e. no dependencies
• Freedom of style and version
• Easy readability
• Code handover
Why prototype syntax
“I have been writing JavaScript for 8 years
now, and I have never once found need to
use an uber func...
Scope
• Scope refers to where variables and
  functions are accessible
• In what context something is being
  executed
• Basically, global or local
• Variables have function scope
• Functions have the same scope as variables
// Global
var likesToPlay = "Poker";

function getGame () {
! // Local
! var likesToPlay = "Hold ‘em";

! // Global
! play...
function playPoker (money) {
! if (money) {
! ! var willPlay = true;
! }

! // Perfectly valid
! return willPlay;
}
function global () {
! return "Access anywhere";
}
function outer () {
! function inner () {
! ! return "Inner";
! }
! return inner();
}
outer(); // Accessible
inner(); // N...
Polluting the global
    namespace
        “Global scope is like a public toilet.

        You can’t avoid going in there....
Function scope
• Run a function in a certain context
• The call and apply methods
• Defined for all functions
function docReady () {
! alert(this);
! // this is the window object
}
window.onload = docReady;
function setName (name) {
! this.name = name;
! // document.name === "Bennifer"
}

document.onclick = function () {
! setN...
function setName (name) {
! this.name = name;
! // document.name === "Bennifer"
}

document.onclick = function () {
! setN...
function setNames () {
! this.firstName = arguments[0];
! this.lastName = arguments[1];
  // document.firstName === “Ben”
...
function setNames () {
! this.firstName = arguments[0];
! this.lastName = arguments[1];
  // document.firstName === “Ben”
...
Closures
• Closures are expressions, usually functions,
  which can work with variables set within a
  certain context
• Inner func...
function add (x) {
! return function (y) {
! ! return x + y;
! };
}
var add5 = add(5);
var no7 = add5(2); // Equals 7
“Right... What?!”
function add (x) {
! return function (y) {
! ! return x + y;
! };
}
var add5 = add(5);

// How JavaScript sees it
var add5...
function add (x) {
! return function (y) {
! ! return x + y;
! };
}
var add5 = add(5);

// How JavaScript sees it
var add5...
function addLinks () {
! for (var i=0, link; i<5; i++) {
! ! link = document.createElement("a");
! ! link.innerHTML = "Lin...
function addLinks () {
! for (var i=0, link; i<5; i++) {
! ! link = document.createElement("a");
! ! link.innerHTML = "Lin...
function addLinks () {
! for (var i=0, link; i<5; i++) {
! ! link = document.createElement("a");
! ! link.innerHTML = "Lin...
function addLinks () {
! for (var i=0, link; i<5; i++) {
! ! link = document.createElement("a");
! ! link.innerHTML = "Lin...
function addLinks () {
! for (var i=0, link; i<5; i++) {
! ! link = document.createElement("a");
! ! link.innerHTML = "Lin...
function addLinks () {
! for (var i=0, link; i<5; i++) {
! ! link = document.createElement("a");
! ! link.innerHTML = "Lin...
function addLinks () {
! for (var i=0, link; i<5; i++) {
! ! link = document.createElement("a");
! ! link.innerHTML = "Lin...
Yahoo JavaScript
Module Pattern
• Origins from Douglas Crockford
• Singleton pattern
• Offers private and public members
var goneBabyGone = function   () {
! // Private members
! var movieTitle = "Gone Baby Gone",
     isDirectedByBen = true;
...
var goneBabyGone = function   () {
! // Private members
! var movieTitle = "Gone Baby Gone",
     isDirectedByBen = true;
...
var goneBabyGone = function   () {
! // Private members
! var movieTitle = "Gone Baby Gone",
     isDirectedByBen = true;
...
var goneBabyGone = function        () {
!   // Private members
!   var movieTitle = "Gone Baby Gone",
         isDirectedB...
Namespacing
• Avoiding global variables
• Code structure
• Extending, but not necessarily inheriting
// Create a Ben object
var Ben = {};


// Set functionality
Ben.Director = function () {
! var noOfMovies = 4;
! return {
...
// Assertion
if (typeof Ben === "undefined") {
! Ben = {};
}
Ben.Actor = function () {
! var noOfMovies = 51;
! return {
!...
Sugar & spice
   It’s awfully nice!
• Sugaring
• Currying
// A little sugar
String.prototype.trim = function () {
!    return this.replace(/^s*|s*$/g, "");
};


var monkey = "     ...
// Currying
function add () {
!   var sum = 0;
!   for (var i=0, il=arguments.length; i<il; i++) {
!   !    sum += argumen...
// Currying (continued) - Currying method by Crockford!
                                                      !
Function.p...
// Currying (continued) - Currying method by Crockford!
                                                      !
Function.p...
// Currying (continued) - Currying method by Crockford!
                                                      !
Function.p...
// Currying (continued) - Currying method by Crockford!
                                                      !
Function.p...
// Currying (continued) - Currying method by Crockford!
                                                      !
Function.p...
// Currying (continued) - Currying method by Crockford!
                                                      !
Function.p...
Syntax
recommendations
• No real standard, only best practices
• Recommended tool: JSLint
Embrace JavaScript
• Embrace JavaScript
• Don’t try to make it into Java, C or any
  other language
• Learn to love it and its dynamic, loose...
This is how we roll
Robert Nyman
                                                        robertnyman.com/speaking/
                           ...
Inheritance
Inheritance
Inheritance
Inheritance
Inheritance
Inheritance
Inheritance
Inheritance
Upcoming SlideShare
Loading in …5
×
42,797 views

Published on

Inheritance

Published in: Technology
  • DOWNLOAD FULL eBOOK INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... 1.DOWNLOAD FULL. PDF eBook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB eBook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. doc eBook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. PDF eBook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB eBook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... 1.DOWNLOAD FULL. doc eBook here { https://tinyurl.com/y3nhqquc } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, CookeBOOK Crime, eeBOOK Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Glad you liked it!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • thanks ,very good
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • pretty good!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Thank you!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

×