SlideShare a Scribd company logo
The JavaScript
Programming Primer
   Scope Context Closures




                               Presentation by
                                  Mike Wilcox
                            February 3rd, 2009
Overview
★ JavaScript Language Overview
  ★ Object

  ★ Array

  ★ Function

★ Scope
★ Context
★ Closures
Is JavaScript Easy?
★ Scripting languages often considered
  simple
★ Loose Typing makes it versatile and
  extremely flexible
★ Functional style allows quick tasks:

myDiv.hide();
image.swap();
myForm.validate(); // with script I found on the Internet
It is not a Toy!
★ Interpreted language not compiled
★ Loosely Typed
★ OO capabilities
★ Resembles C, C++ and Java in some syntax only
★ Uses prototype for inheritance like Self
Mutable
 All JavaScript objects,
 including the native objects,
 can be added to or extended


 String.prototype.reverse = function(){
     return this.split("").reverse().join("");
 }
 var a = "Club Ajax";
 console.log(a.reverse()); // xajA bulC
Mutable
 So exactly how “mutable” is
 JavaScript anyway?



 Array = function(){
    alert("JavaScript no longer has Arrays.");
 }
 var a = new Array("club", "ajax");
Object
Object Defined
A JavaScript object is a composite datatype containing an
unordered collection of variables and methods.
 ★ All objects are a hash map and everything is an object
 ★ All JavaScript objects are mutable - even the built in
   methods and properties can be changed.
 ★ An object variable is a property - like a field in Java
 ★ Can contain any type of data - even functions
Object Definitions
  Creating an object by Definition, using the object’s
  constructor function

obj = new Object();
obj.prop = "Club AJAX"
obj.subObj = new Object();
obj.subObj.location = “Dallas”;
obj.subObj.when = new Date("2/3/2009");
Object Literals
    Creating an object with the Literal syntax - also known
    as an initializer


   name = {prefix:"Club", suffix:"AJAX"};

    obj = {

   
 fullname: name.prefix + name.suffix,

   
 deep:{

   
 
 fullname: name.prefix + “ “ + name.suffix

   
 }

   };
Object - Value Access
// dot syntax
image.width;
image.height;
obj.myDomElement;
obj.myFunction;
obj.myArray;
// associative array
obj["myDomElement"];
obj["myFunction"];
obj["myArray"];


var i = “myArray”;
obj["myArray"] = obj["my” + ”Array"] = obj[i] = obj.myArray;
Array
Array in Brief
★ An untyped, ordered object
★ Has a length property
★ Additional methods: push(), pop(), etc.
// Definition

 var a = new Array(10); // sets length
   var b = new Array(“club”, “ajax”); // sets array
// Literal

 var c = ["club", "ajax"];

 c[2] = "rocks";
// Bad form!

 myArray["prop"] = "associative"; // works but unexpected
Function
Functions
Unlike Java, Functions are literal data values that can be
manipulated. They can be assigned to variables, properties
of objects, the elements of an array, or passed as
arguments.*
 ★ Concept borrowed from Lisp Lambda functions
 ★ Functions are first class objects
 ★ Functions are objects with executable code
 ★ Can be used as constructors for object instances**
 ★ Used as a literal or a definition
* JavaScript - The Definitive Guide
** Function constructors will be covered in the presentation about Inheritance.
Function Definition
 Function Definition created by the function
 keyword:

function ninja(){

 return "ninja";
}
Function Literal
★ An expression that defines an unnamed function
★ Also called Function Statement or an Anonymous
  Function or a Function Expression
★ Much more flexible than Definitions, as they can used
  once and need not be named*
  // Unnamed Function assigned to "foo":
    f[0] = function(x){ return x * x;}
    myArray.sort(function(a,b){ return a<b; });
    var squared = (function(n){ return n*n })(num);




*JavaScript the Definitive Guide
Function Literal Usage
 // Stored as a variable:
 ar[1] = function(x){ return x * x; }
 ar[1](2); // 4

 // Passed as an argument:
 var add = function( a, b ){
   return a() + b();
 }
 add(function(){ return 1; }, function(){ return 2; }); // 3


 // Invoked Directly:
 var foo = (function(){ return "bar"; })();
 // foo = "bar", the result of the invoked function,
 // not the function itself
Assigning a Literal to Definition
 Allows the body of the function to refer to the Literal


 var f = function factor(x,   num){
 
    if(x==0){
 
    
 return num;
 
    }else{
 
       return factor(x-1,   num+=x)
 
    }
 }
 console.log(f(3, 0));        // 6
 console.log(factor(3, 0));   // ERROR factor is undefined
Function as a Method
  A function can be added to any object at any time


var dimensions = {width: 10, height: 5};

dimensions.getArea = function() {
  return this.width * this.height;
}
Scope
Scope
 ★ Scope is an enclosing context where values and
   expressions are associated and is used to define the
   visibility and reach of information hiding*
 ★ JavaScript uses a lexical (or static) scope scheme,
   meaning that the scope is created and variables are
   bound when the code is defined, not when executed




http://en.wikipedia.org/wiki/Scope_(programming)
Scope - Simple Example
★ Functions can see the scope outside them, but not
  inside of them
  var assassin = "Ninja";
  function getWarrior(){
  
    alert(assassin); // SUCCESS!
  }


  function setWarrior(){
      var warrior = "Ninja";
  }
  alert(warrior); // FAILS!
Scope Diagram
The scope chain
resembles a hierarchal
tree, much like that of
classical inheritance                 scope


                              scope           scope


               scope           scope          scope           scope


   scope           scope       scope                  scope       scope


           scope           scope                              scope       scope
Scope Diagram
Like classical
inheritance, the
children can see their
ancestors, but parents                scope
cannot see their
descendants                                   scope
                              scope


               scope           scope          scope           scope


   scope           scope       scope                  scope       scope


           scope           scope                              scope       scope
Scope Diagram

                                    scope


                            scope           scope


             scope           scope          scope           scope


 scope           scope       scope                  scope       scope


         scope           scope                              scope       scope
Scope - Objects
★ Objects don’t create a scope (they create context), but
  they are able to access scope:

  var first = “kick”;
  var myObject = {
      type:first,   // scope captured here
      attack: function(){
          return this.type;
      }
  }
  alert(myObject.attack());
Scope - No Blocks
 No block-level scope, unlike C, C++, and Java

 function scoping(){
 
    var a = 1;
 
    for(var i=0, len=20; i < len; i++){
 
    
 if(i==10){
 
    
 
 var b = i;
 
    
 
 break;
 
    
 }
 
    }
 
    while(b<20){
 
    
 b++;
 
    }
 
    console.log(a + i + len + b);
      // 51 - no errors, all defined
 }
Scope - Activation
 Variables declared within a function are defined
 throughout the function

 var hero = "Spider-man"
 function scoping(){
 
    alert(hero);   // - output ?
 
    var hero = "Dr. Octopus";
 
    alert(hero);   // - output ?
 }
Hey what is var anyway?
   The var statement defines a variable by creating a
   property with that name in the body of an enclosing
   function. If the declaration is not within a function
   body, it is declared in the global scope.*

   var   i;
   var   x =   10;
   var   w =   20, y = 30, h = 100;
   var   f =   function(arg){
         var   a = 1;
         var   arg = arg + 1; // - result ?
   }


*JavaScript the Definitive guide
Scope Global
★ In a browser, the window is global
★ Global scope is special because it is the end of the
  scope chain, and since it is an object, it has context
★ The following all mean the same thing, in the global
  scope only:
  <script>
  
    window.weapon = "katana";
  
    weapon = "katana";
 
 
  
    var weapon = "katana";
  
    this.weapon = "katana";
  </script>
Scope Accidental Globals
 Regardless of the depth of the scope, not using var
 always assigns the variable as a global

 transportation = “horse”;
 alert("Ninja rides a:", transportation); // - output ?
 function ride(){
 
    transportation = "Kawasaki";
 
    alert("Ninja rides a:", transportation); // - ?
 }
 alert("Ninja rides a:", transportation); // - output ?
Context
Context
★ Context is a method’s reference to an object
★ A function and a method are different!
★ A method has context to the object to which it
  belongs (a function does not)
★ Whereas scope is lexical and can be determined by
  the program code, context is executional, and is
  determined at runtime
★ Tip: scope belongs to functions, and context belongs
  to objects
Context - this
 ★ A method has a very important keyword: this
 ★ A method’s value of this becomes the object that
   invoked it
 ★ Context can be thought of as this*
 ★ this cannot be explicitly set, but it can be changed
 ★ Change this with either call() or apply()
 ★ JavaScript libraries usually have convenience
   functions to change this

*Execution context actually has a broader meaning that includes scope, which is
an advanced topic.
Context vs Scope
★ Context refers to an object and its properties and
  methods
★ Scope refers to local functions and variables,
  irrespective of the object or its context
  var myObject = {
      init: function(){
          this.myProperty = “prop”;
          this.myMethod = function(){ ... }


          var myVariable = “value”;
          var myFunction = function(){ ... }
      }
  }
Context - Example
 var attire = {
 
    ring:"shobo",
     init = function(){
 
       return this.ring;
     }
 }
 attire.init(); // context of attire applied to init()
"this" is confusing!
 If context is not set, regardless of scope, this will
 default to the global object

 function testNoContext(){
     
var location = "here";

        // local variable, not a context property
     
alert(this.location);
        // returns the window.location object
 }
 
    
 function testNoContext(){
    locashion = "TYPO";
    alert(location);
       // returns the window.location object
 }
Context - Maintaining
 When one object calls another, it can sometimes be
 confusing to know in which context you are
 var a = {
 
    objectId: "A",
 
    doCall: function(){
 
    
 return this.objectId;
 
    }
 };
 var b = {
 
    objectId: "B",
 
    callOther: function(){
 
    
 return a.doCall();
 
    }
 };
 alert(b.callOther()); // - result ?
Context - Maintaining
 Using call() gets a different result


 var a = {
 
    objectId: "A",
 
    doCall: function(){
 
    
 return this.objectId;
 
    }
 };
 var b = {
 
    objectId: "B",
 
    callOther: function(){
 
    
 return a.doCall.call(a);
 
    }
 };
 alert(b.callOther()); // - result ?
Context - Changing
 Context often "fixed" in "functions" with this pattern:

 var self = this;
 var myFunc = function(){
 
    self.doMethod();
 }
 myFunc();
dojo.hitch
 dojo.hitch changes context for you, using apply() in the
 background

 myFunc = function(){
 
    this.doMethod();
 }
 dojo.hitch(this, myFunc)();
 // or:
 myFunc = dojo.hitch(this, function(){
     this.doMethod();
 });
Context - setTimeout
 setTimeout is often awkward due to context. dojo.hitch
 fixes this:

 setTimeout(dojo.hitch(this, function(){
 
    this.battle = this.doEvil + this.doGood;
 
    this.getConflicted();
 }), 500);
Context - Anonymous Functions
 desc
 var o = {
 
    objectId: "A",
 
    docall:function(){
 
    
 alert(this.objectId);
 
    },
 
    init: function(){
 
    
 var callCall = dojo.hitch(this, function(){
 
    
 
 this.docall();
 
    
 });
 
    
 var cc = function(){
 
    
 
 this.docall();
 
    
 }
 
    
 callCall();               // - result ?
 
    
 dojo.hitch(this, cc)();   // - result ?
 
    
 cc.call(this);            // - result ?
 
    }
 }
Closures
Closures
★ By definition, closures operate in the execution
  context and are a combination of scope and code
★ The result of invoking a function that captures a
  variable outside of its scope
★ Closures are not bad - they are quite powerful
★ However:
  ★ They can consume more memory

  ★ Creating a circular reference with a DOM node in IE is what
    causes memory leaks
Closures - Simple Example
 saveForLater = function(){
     var weapon = “throwing stars”;
     return function(){
         return weapon; // captures ‘a’
     }
 }
 var device = saveForLater(); // - result ?

 setTimeout(function(){
   alert(device()); // - result ?
 }, 1000);


 var doItNow = saveForLater()();    // - result ?
Closures - Private Variables
 var count = new (function(){
     var num = 0;
     return function() { return num++ }
 })();


 alert(count());
 alert(count());
 alert(count());
Memory Leak Example
 The onclick function creates a scope and captures the
 node variable. The GC can’t remove node because it is
 used by onclick, and it can’t remove the DOM
 element because the node variable refers to it.
 function attach(){
 
    var node = document.createElement("div");
 
    node.onclick = function(){
 
    
 alert("clicked" + node);
 
    }
 }
Memory Leak Fixed
 The following shows how to do your own GC chores.
 Note that most JavaScript libraries will handle this for
 you in the background.

 function attach(){
 
    var node = document.createElement("div");
 
    node.onclick = function(){
 
    
 alert("clicked" + node);
 
    }
     window.onunload = function(){
         node.onclick = null;
         window.onunload = null;
     }
 }
dojo.connect
 dojo.connect is specifically designed for preventing
 for preventing memory leaks

 var doClick = function(event){
     if(event.type==”onclick”){
         alert(“clicked”);
     }
   }
 var node = document.createElement("div");
 var ref = dojo.connect(node, “click”, window, doClick);

 // when window unloads, dojo will disconnect:
 dojo.disconnect(ref);
References
JavaScript Closures - Jim Ley
http://www.jibbering.com/faq/faq_notes/closures.html#clIRExSc

Lexical Scoping
http://blogs.msdn.com/kartikb/archive/2009/01/15/lexical-scoping.aspx

Closures and IE Circular References - Scott Isaacs
http://siteexperts.spaces.live.com/Blog/cns!1pNcL8JwTfkkjv4gg6LkVCpw!338.entry

kartikbansal
http://blogs.msdn.com/kartikb/archive/2009/01/15/lexical-scoping.aspx

WikiPedia
http://en.wikipedia.org/wiki/Scope_(programming)

Mozilla JavaScript Spec
http://www.mozilla.org/js/language/E262-3.pdfs

JavaScript - The Definitive Guide by David Flanagan
The JavaScript  Programming Primer

More Related Content

What's hot

JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
What lies beneath the beautiful code?
What lies beneath the beautiful code?What lies beneath the beautiful code?
What lies beneath the beautiful code?
Niranjan Sarade
 
Ruby Internals
Ruby InternalsRuby Internals
Ruby Internals
Burke Libbey
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
David Atchley
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
JavaScript OOPs
JavaScript OOPsJavaScript OOPs
JavaScript OOPs
Johnson Chou
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
msemenistyi
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
Robert Nyman
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Cappuccino
CappuccinoCappuccino
Cappuccino
Jelle Vandebeeck
 
Java script
Java scriptJava script
Java script
Adrian Caetano
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
Folio3 Software
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange
 

What's hot (20)

JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
What lies beneath the beautiful code?
What lies beneath the beautiful code?What lies beneath the beautiful code?
What lies beneath the beautiful code?
 
Ruby Internals
Ruby InternalsRuby Internals
Ruby Internals
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
JavaScript OOPs
JavaScript OOPsJavaScript OOPs
JavaScript OOPs
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Cappuccino
CappuccinoCappuccino
Cappuccino
 
Java script
Java scriptJava script
Java script
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 

Viewers also liked

Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
IJSRD
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
T11 Sessions
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
Mindy McAdams
 
Paris Web - Javascript as a programming language
Paris Web - Javascript as a programming languageParis Web - Javascript as a programming language
Paris Web - Javascript as a programming language
Marco Cedaro
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScript
Codemotion
 
Javascript Tutorial
Javascript TutorialJavascript Tutorial
Javascript Tutorial
Kang-min Liu
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript Programming
Collaboration Technologies
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
Troy Miles
 
Biomass gasifier pune
Biomass gasifier  puneBiomass gasifier  pune
Biomass gasifier puneroad2ideas
 
Downdraft biomass gasification: experimental investigation and aspen plus sim...
Downdraft biomass gasification: experimental investigation and aspen plus sim...Downdraft biomass gasification: experimental investigation and aspen plus sim...
Downdraft biomass gasification: experimental investigation and aspen plus sim...
Antonio Geraldo de Paula Oliveira
 
Biomass Gasification presentation
Biomass Gasification presentationBiomass Gasification presentation
Biomass Gasification presentationPritish Shardul
 
Bio Mass Gasifier
Bio Mass GasifierBio Mass Gasifier
Biomass Gasification
Biomass GasificationBiomass Gasification
Biomass Gasification
Er Soumyabrata Basak
 
Biomass heat and power - gasification CHP with universal biomass gasifier
Biomass heat and power - gasification CHP with universal biomass gasifierBiomass heat and power - gasification CHP with universal biomass gasifier
Biomass heat and power - gasification CHP with universal biomass gasifier
Rado Irgl
 
biomass gasification
biomass gasificationbiomass gasification
biomass gasification
Akepati S. Reddy
 
Biomass gassifier
Biomass gassifierBiomass gassifier
Biomass gassifier
Aravind Rajan
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
Rasan Samarasinghe
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Bryan Basham
 
Object oriented programming in JavaScript
Object oriented programming in JavaScriptObject oriented programming in JavaScript
Object oriented programming in JavaScript
Aditya Majety
 

Viewers also liked (20)

Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Paris Web - Javascript as a programming language
Paris Web - Javascript as a programming languageParis Web - Javascript as a programming language
Paris Web - Javascript as a programming language
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScript
 
Javascript Tutorial
Javascript TutorialJavascript Tutorial
Javascript Tutorial
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript Programming
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
 
Biomass gasifier pune
Biomass gasifier  puneBiomass gasifier  pune
Biomass gasifier pune
 
Downdraft biomass gasification: experimental investigation and aspen plus sim...
Downdraft biomass gasification: experimental investigation and aspen plus sim...Downdraft biomass gasification: experimental investigation and aspen plus sim...
Downdraft biomass gasification: experimental investigation and aspen plus sim...
 
Biomass Gasification presentation
Biomass Gasification presentationBiomass Gasification presentation
Biomass Gasification presentation
 
Bio Mass Gasifier
Bio Mass GasifierBio Mass Gasifier
Bio Mass Gasifier
 
Biomass Gasification
Biomass GasificationBiomass Gasification
Biomass Gasification
 
Biomass heat and power - gasification CHP with universal biomass gasifier
Biomass heat and power - gasification CHP with universal biomass gasifierBiomass heat and power - gasification CHP with universal biomass gasifier
Biomass heat and power - gasification CHP with universal biomass gasifier
 
biomass gasification
biomass gasificationbiomass gasification
biomass gasification
 
Biomass gassifier
Biomass gassifierBiomass gassifier
Biomass gassifier
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Object oriented programming in JavaScript
Object oriented programming in JavaScriptObject oriented programming in JavaScript
Object oriented programming in JavaScript
 

Similar to The JavaScript Programming Primer

JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
Sarvesh Kushwaha
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
Paweł Dorofiejczyk
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
Eugene Lazutkin
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
Ran Mizrahi
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
Ivano Malavolta
 
JavaScript
JavaScriptJavaScript
JavaScript
Ivano Malavolta
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
Radoslav Georgiev
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closures
HDR1001
 
Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Sopheak Sem
 
JavsScript OOP
JavsScript OOPJavsScript OOP
JavsScript OOP
LearningTech
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
Nir Noy
 
Core java concepts
Core java conceptsCore java concepts
Core java concepts
laratechnologies
 

Similar to The JavaScript Programming Primer (20)

JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
oojs
oojsoojs
oojs
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
JavaScript
JavaScriptJavaScript
JavaScript
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Week3
Week3Week3
Week3
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closures
 
Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02
 
JavsScript OOP
JavsScript OOPJavsScript OOP
JavsScript OOP
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Core java concepts
Core java conceptsCore java concepts
Core java concepts
 

More from Mike Wilcox

Accessibility for Fun and Profit
Accessibility for Fun and ProfitAccessibility for Fun and Profit
Accessibility for Fun and Profit
Mike Wilcox
 
WTF R PWAs?
WTF R PWAs?WTF R PWAs?
WTF R PWAs?
Mike Wilcox
 
Advanced React
Advanced ReactAdvanced React
Advanced React
Mike Wilcox
 
Webpack: What it is, What it does, Whether you need it
Webpack: What it is, What it does, Whether you need itWebpack: What it is, What it does, Whether you need it
Webpack: What it is, What it does, Whether you need it
Mike Wilcox
 
Dangerous CSS
Dangerous CSSDangerous CSS
Dangerous CSS
Mike Wilcox
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
Mike Wilcox
 
Great Responsive-ability Web Design
Great Responsive-ability Web DesignGreat Responsive-ability Web Design
Great Responsive-ability Web Design
Mike Wilcox
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatterns
Mike Wilcox
 
Model View Madness
Model View MadnessModel View Madness
Model View Madness
Mike Wilcox
 
Hardcore JavaScript – Write it Right
Hardcore JavaScript – Write it RightHardcore JavaScript – Write it Right
Hardcore JavaScript – Write it Right
Mike Wilcox
 
The Great Semicolon Debate
The Great Semicolon DebateThe Great Semicolon Debate
The Great Semicolon Debate
Mike Wilcox
 
AMD - Why, What and How
AMD - Why, What and HowAMD - Why, What and How
AMD - Why, What and How
Mike Wilcox
 
Dojo & HTML5
Dojo & HTML5Dojo & HTML5
Dojo & HTML5
Mike Wilcox
 
Webpage Design Basics for Non-Designers
Webpage Design Basics for Non-DesignersWebpage Design Basics for Non-Designers
Webpage Design Basics for Non-DesignersMike Wilcox
 
Why You Need a Front End Developer
Why You Need a Front End DeveloperWhy You Need a Front End Developer
Why You Need a Front End Developer
Mike Wilcox
 
A Conversation About REST
A Conversation About RESTA Conversation About REST
A Conversation About REST
Mike Wilcox
 
The Fight Over HTML5
The Fight Over HTML5The Fight Over HTML5
The Fight Over HTML5
Mike Wilcox
 
The Fight Over HTML5
The Fight Over HTML5The Fight Over HTML5
The Fight Over HTML5
Mike Wilcox
 
How to get a Job as a Front End Developer
How to get a Job as a Front End DeveloperHow to get a Job as a Front End Developer
How to get a Job as a Front End Developer
Mike Wilcox
 
The History of HTML5
The History of HTML5The History of HTML5
The History of HTML5
Mike Wilcox
 

More from Mike Wilcox (20)

Accessibility for Fun and Profit
Accessibility for Fun and ProfitAccessibility for Fun and Profit
Accessibility for Fun and Profit
 
WTF R PWAs?
WTF R PWAs?WTF R PWAs?
WTF R PWAs?
 
Advanced React
Advanced ReactAdvanced React
Advanced React
 
Webpack: What it is, What it does, Whether you need it
Webpack: What it is, What it does, Whether you need itWebpack: What it is, What it does, Whether you need it
Webpack: What it is, What it does, Whether you need it
 
Dangerous CSS
Dangerous CSSDangerous CSS
Dangerous CSS
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
Great Responsive-ability Web Design
Great Responsive-ability Web DesignGreat Responsive-ability Web Design
Great Responsive-ability Web Design
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatterns
 
Model View Madness
Model View MadnessModel View Madness
Model View Madness
 
Hardcore JavaScript – Write it Right
Hardcore JavaScript – Write it RightHardcore JavaScript – Write it Right
Hardcore JavaScript – Write it Right
 
The Great Semicolon Debate
The Great Semicolon DebateThe Great Semicolon Debate
The Great Semicolon Debate
 
AMD - Why, What and How
AMD - Why, What and HowAMD - Why, What and How
AMD - Why, What and How
 
Dojo & HTML5
Dojo & HTML5Dojo & HTML5
Dojo & HTML5
 
Webpage Design Basics for Non-Designers
Webpage Design Basics for Non-DesignersWebpage Design Basics for Non-Designers
Webpage Design Basics for Non-Designers
 
Why You Need a Front End Developer
Why You Need a Front End DeveloperWhy You Need a Front End Developer
Why You Need a Front End Developer
 
A Conversation About REST
A Conversation About RESTA Conversation About REST
A Conversation About REST
 
The Fight Over HTML5
The Fight Over HTML5The Fight Over HTML5
The Fight Over HTML5
 
The Fight Over HTML5
The Fight Over HTML5The Fight Over HTML5
The Fight Over HTML5
 
How to get a Job as a Front End Developer
How to get a Job as a Front End DeveloperHow to get a Job as a Front End Developer
How to get a Job as a Front End Developer
 
The History of HTML5
The History of HTML5The History of HTML5
The History of HTML5
 

Recently uploaded

Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 

Recently uploaded (20)

Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 

The JavaScript Programming Primer

  • 1. The JavaScript Programming Primer Scope Context Closures Presentation by Mike Wilcox February 3rd, 2009
  • 2. Overview ★ JavaScript Language Overview ★ Object ★ Array ★ Function ★ Scope ★ Context ★ Closures
  • 3. Is JavaScript Easy? ★ Scripting languages often considered simple ★ Loose Typing makes it versatile and extremely flexible ★ Functional style allows quick tasks: myDiv.hide(); image.swap(); myForm.validate(); // with script I found on the Internet
  • 4. It is not a Toy! ★ Interpreted language not compiled ★ Loosely Typed ★ OO capabilities ★ Resembles C, C++ and Java in some syntax only ★ Uses prototype for inheritance like Self
  • 5. Mutable All JavaScript objects, including the native objects, can be added to or extended String.prototype.reverse = function(){ return this.split("").reverse().join(""); } var a = "Club Ajax"; console.log(a.reverse()); // xajA bulC
  • 6. Mutable So exactly how “mutable” is JavaScript anyway? Array = function(){ alert("JavaScript no longer has Arrays."); } var a = new Array("club", "ajax");
  • 8. Object Defined A JavaScript object is a composite datatype containing an unordered collection of variables and methods. ★ All objects are a hash map and everything is an object ★ All JavaScript objects are mutable - even the built in methods and properties can be changed. ★ An object variable is a property - like a field in Java ★ Can contain any type of data - even functions
  • 9. Object Definitions Creating an object by Definition, using the object’s constructor function obj = new Object(); obj.prop = "Club AJAX" obj.subObj = new Object(); obj.subObj.location = “Dallas”; obj.subObj.when = new Date("2/3/2009");
  • 10. Object Literals Creating an object with the Literal syntax - also known as an initializer name = {prefix:"Club", suffix:"AJAX"}; obj = { fullname: name.prefix + name.suffix, deep:{ fullname: name.prefix + “ “ + name.suffix } };
  • 11. Object - Value Access // dot syntax image.width; image.height; obj.myDomElement; obj.myFunction; obj.myArray; // associative array obj["myDomElement"]; obj["myFunction"]; obj["myArray"]; var i = “myArray”; obj["myArray"] = obj["my” + ”Array"] = obj[i] = obj.myArray;
  • 12. Array
  • 13. Array in Brief ★ An untyped, ordered object ★ Has a length property ★ Additional methods: push(), pop(), etc. // Definition var a = new Array(10); // sets length var b = new Array(“club”, “ajax”); // sets array // Literal var c = ["club", "ajax"]; c[2] = "rocks"; // Bad form! myArray["prop"] = "associative"; // works but unexpected
  • 15. Functions Unlike Java, Functions are literal data values that can be manipulated. They can be assigned to variables, properties of objects, the elements of an array, or passed as arguments.* ★ Concept borrowed from Lisp Lambda functions ★ Functions are first class objects ★ Functions are objects with executable code ★ Can be used as constructors for object instances** ★ Used as a literal or a definition * JavaScript - The Definitive Guide ** Function constructors will be covered in the presentation about Inheritance.
  • 16. Function Definition Function Definition created by the function keyword: function ninja(){ return "ninja"; }
  • 17. Function Literal ★ An expression that defines an unnamed function ★ Also called Function Statement or an Anonymous Function or a Function Expression ★ Much more flexible than Definitions, as they can used once and need not be named* // Unnamed Function assigned to "foo": f[0] = function(x){ return x * x;} myArray.sort(function(a,b){ return a<b; }); var squared = (function(n){ return n*n })(num); *JavaScript the Definitive Guide
  • 18. Function Literal Usage // Stored as a variable: ar[1] = function(x){ return x * x; } ar[1](2); // 4 // Passed as an argument: var add = function( a, b ){ return a() + b(); } add(function(){ return 1; }, function(){ return 2; }); // 3 // Invoked Directly: var foo = (function(){ return "bar"; })(); // foo = "bar", the result of the invoked function, // not the function itself
  • 19. Assigning a Literal to Definition Allows the body of the function to refer to the Literal var f = function factor(x, num){ if(x==0){ return num; }else{ return factor(x-1, num+=x) } } console.log(f(3, 0)); // 6 console.log(factor(3, 0)); // ERROR factor is undefined
  • 20. Function as a Method A function can be added to any object at any time var dimensions = {width: 10, height: 5}; dimensions.getArea = function() {   return this.width * this.height; }
  • 21. Scope
  • 22. Scope ★ Scope is an enclosing context where values and expressions are associated and is used to define the visibility and reach of information hiding* ★ JavaScript uses a lexical (or static) scope scheme, meaning that the scope is created and variables are bound when the code is defined, not when executed http://en.wikipedia.org/wiki/Scope_(programming)
  • 23. Scope - Simple Example ★ Functions can see the scope outside them, but not inside of them var assassin = "Ninja"; function getWarrior(){ alert(assassin); // SUCCESS! } function setWarrior(){ var warrior = "Ninja"; } alert(warrior); // FAILS!
  • 24. Scope Diagram The scope chain resembles a hierarchal tree, much like that of classical inheritance scope scope scope scope scope scope scope scope scope scope scope scope scope scope scope scope
  • 25. Scope Diagram Like classical inheritance, the children can see their ancestors, but parents scope cannot see their descendants scope scope scope scope scope scope scope scope scope scope scope scope scope scope scope
  • 26. Scope Diagram scope scope scope scope scope scope scope scope scope scope scope scope scope scope scope scope
  • 27. Scope - Objects ★ Objects don’t create a scope (they create context), but they are able to access scope: var first = “kick”; var myObject = { type:first, // scope captured here attack: function(){ return this.type; } } alert(myObject.attack());
  • 28. Scope - No Blocks No block-level scope, unlike C, C++, and Java function scoping(){ var a = 1; for(var i=0, len=20; i < len; i++){ if(i==10){ var b = i; break; } } while(b<20){ b++; } console.log(a + i + len + b); // 51 - no errors, all defined }
  • 29. Scope - Activation Variables declared within a function are defined throughout the function var hero = "Spider-man" function scoping(){ alert(hero); // - output ? var hero = "Dr. Octopus"; alert(hero); // - output ? }
  • 30. Hey what is var anyway? The var statement defines a variable by creating a property with that name in the body of an enclosing function. If the declaration is not within a function body, it is declared in the global scope.* var i; var x = 10; var w = 20, y = 30, h = 100; var f = function(arg){ var a = 1; var arg = arg + 1; // - result ? } *JavaScript the Definitive guide
  • 31. Scope Global ★ In a browser, the window is global ★ Global scope is special because it is the end of the scope chain, and since it is an object, it has context ★ The following all mean the same thing, in the global scope only: <script> window.weapon = "katana"; weapon = "katana"; var weapon = "katana"; this.weapon = "katana"; </script>
  • 32. Scope Accidental Globals Regardless of the depth of the scope, not using var always assigns the variable as a global transportation = “horse”; alert("Ninja rides a:", transportation); // - output ? function ride(){ transportation = "Kawasaki"; alert("Ninja rides a:", transportation); // - ? } alert("Ninja rides a:", transportation); // - output ?
  • 34. Context ★ Context is a method’s reference to an object ★ A function and a method are different! ★ A method has context to the object to which it belongs (a function does not) ★ Whereas scope is lexical and can be determined by the program code, context is executional, and is determined at runtime ★ Tip: scope belongs to functions, and context belongs to objects
  • 35. Context - this ★ A method has a very important keyword: this ★ A method’s value of this becomes the object that invoked it ★ Context can be thought of as this* ★ this cannot be explicitly set, but it can be changed ★ Change this with either call() or apply() ★ JavaScript libraries usually have convenience functions to change this *Execution context actually has a broader meaning that includes scope, which is an advanced topic.
  • 36. Context vs Scope ★ Context refers to an object and its properties and methods ★ Scope refers to local functions and variables, irrespective of the object or its context var myObject = { init: function(){ this.myProperty = “prop”; this.myMethod = function(){ ... } var myVariable = “value”; var myFunction = function(){ ... } } }
  • 37. Context - Example var attire = { ring:"shobo", init = function(){ return this.ring; } } attire.init(); // context of attire applied to init()
  • 38. "this" is confusing! If context is not set, regardless of scope, this will default to the global object function testNoContext(){ var location = "here"; // local variable, not a context property alert(this.location); // returns the window.location object } function testNoContext(){ locashion = "TYPO"; alert(location); // returns the window.location object }
  • 39. Context - Maintaining When one object calls another, it can sometimes be confusing to know in which context you are var a = { objectId: "A", doCall: function(){ return this.objectId; } }; var b = { objectId: "B", callOther: function(){ return a.doCall(); } }; alert(b.callOther()); // - result ?
  • 40. Context - Maintaining Using call() gets a different result var a = { objectId: "A", doCall: function(){ return this.objectId; } }; var b = { objectId: "B", callOther: function(){ return a.doCall.call(a); } }; alert(b.callOther()); // - result ?
  • 41. Context - Changing Context often "fixed" in "functions" with this pattern: var self = this; var myFunc = function(){ self.doMethod(); } myFunc();
  • 42. dojo.hitch dojo.hitch changes context for you, using apply() in the background myFunc = function(){ this.doMethod(); } dojo.hitch(this, myFunc)(); // or: myFunc = dojo.hitch(this, function(){ this.doMethod(); });
  • 43. Context - setTimeout setTimeout is often awkward due to context. dojo.hitch fixes this: setTimeout(dojo.hitch(this, function(){ this.battle = this.doEvil + this.doGood; this.getConflicted(); }), 500);
  • 44. Context - Anonymous Functions desc var o = { objectId: "A", docall:function(){ alert(this.objectId); }, init: function(){ var callCall = dojo.hitch(this, function(){ this.docall(); }); var cc = function(){ this.docall(); } callCall(); // - result ? dojo.hitch(this, cc)(); // - result ? cc.call(this); // - result ? } }
  • 46. Closures ★ By definition, closures operate in the execution context and are a combination of scope and code ★ The result of invoking a function that captures a variable outside of its scope ★ Closures are not bad - they are quite powerful ★ However: ★ They can consume more memory ★ Creating a circular reference with a DOM node in IE is what causes memory leaks
  • 47. Closures - Simple Example saveForLater = function(){ var weapon = “throwing stars”; return function(){ return weapon; // captures ‘a’ } } var device = saveForLater(); // - result ? setTimeout(function(){ alert(device()); // - result ? }, 1000); var doItNow = saveForLater()(); // - result ?
  • 48. Closures - Private Variables var count = new (function(){ var num = 0; return function() { return num++ } })(); alert(count()); alert(count()); alert(count());
  • 49. Memory Leak Example The onclick function creates a scope and captures the node variable. The GC can’t remove node because it is used by onclick, and it can’t remove the DOM element because the node variable refers to it. function attach(){ var node = document.createElement("div"); node.onclick = function(){ alert("clicked" + node); } }
  • 50. Memory Leak Fixed The following shows how to do your own GC chores. Note that most JavaScript libraries will handle this for you in the background. function attach(){ var node = document.createElement("div"); node.onclick = function(){ alert("clicked" + node); } window.onunload = function(){ node.onclick = null; window.onunload = null; } }
  • 51. dojo.connect dojo.connect is specifically designed for preventing for preventing memory leaks var doClick = function(event){ if(event.type==”onclick”){ alert(“clicked”); } } var node = document.createElement("div"); var ref = dojo.connect(node, “click”, window, doClick); // when window unloads, dojo will disconnect: dojo.disconnect(ref);
  • 52. References JavaScript Closures - Jim Ley http://www.jibbering.com/faq/faq_notes/closures.html#clIRExSc Lexical Scoping http://blogs.msdn.com/kartikb/archive/2009/01/15/lexical-scoping.aspx Closures and IE Circular References - Scott Isaacs http://siteexperts.spaces.live.com/Blog/cns!1pNcL8JwTfkkjv4gg6LkVCpw!338.entry kartikbansal http://blogs.msdn.com/kartikb/archive/2009/01/15/lexical-scoping.aspx WikiPedia http://en.wikipedia.org/wiki/Scope_(programming) Mozilla JavaScript Spec http://www.mozilla.org/js/language/E262-3.pdfs JavaScript - The Definitive Guide by David Flanagan

Editor's Notes