SlideShare a Scribd company logo
1 of 53
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

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

Biomass gasifier pune
Biomass gasifier  puneBiomass gasifier  pune
Biomass gasifier pune
road2ideas
 
Biomass Gasification presentation
Biomass Gasification presentationBiomass Gasification presentation
Biomass Gasification presentation
Pritish Shardul
 

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 Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 
Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02
Sopheak Sem
 

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

Webpage Design Basics for Non-Designers
Webpage Design Basics for Non-DesignersWebpage Design Basics for Non-Designers
Webpage Design Basics for Non-Designers
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

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

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