SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptStoyan Stefanov
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid 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 ScriptFolio3 Software
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 

Was ist angesagt? (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
 

Andere mochten auch

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 LanguageRaghavan Mohan
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScriptT11 Sessions
 
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 languageMarco Cedaro
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScriptCodemotion
 
Javascript Tutorial
Javascript TutorialJavascript Tutorial
Javascript TutorialKang-min Liu
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScriptTroy 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
 
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 gasifierRado Irgl
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScriptRasan Samarasinghe
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptBryan Basham
 
Object oriented programming in JavaScript
Object oriented programming in JavaScriptObject oriented programming in JavaScript
Object oriented programming in JavaScriptAditya Majety
 

Andere mochten auch (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
 

Ähnlich wie The JavaScript Programming Primer

JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp DeveloperSarvesh Kushwaha
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced FunctionsWebStackAcademy
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald 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 TrainingRadoslav 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 & closuresHDR1001
 
Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Sopheak Sem
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsNir Noy
 

Ähnlich wie 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
 

Mehr von Mike Wilcox

Accessibility for Fun and Profit
Accessibility for Fun and ProfitAccessibility for Fun and Profit
Accessibility for Fun and ProfitMike 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 itMike Wilcox
 
Web Components v1
Web Components v1Web Components v1
Web Components v1Mike Wilcox
 
Great Responsive-ability Web Design
Great Responsive-ability Web DesignGreat Responsive-ability Web Design
Great Responsive-ability Web DesignMike Wilcox
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsMike Wilcox
 
Model View Madness
Model View MadnessModel View Madness
Model View MadnessMike Wilcox
 
Hardcore JavaScript – Write it Right
Hardcore JavaScript – Write it RightHardcore JavaScript – Write it Right
Hardcore JavaScript – Write it RightMike Wilcox
 
The Great Semicolon Debate
The Great Semicolon DebateThe Great Semicolon Debate
The Great Semicolon DebateMike Wilcox
 
AMD - Why, What and How
AMD - Why, What and HowAMD - Why, What and How
AMD - Why, What and HowMike 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 DeveloperMike Wilcox
 
A Conversation About REST
A Conversation About RESTA Conversation About REST
A Conversation About RESTMike Wilcox
 
The Fight Over HTML5
The Fight Over HTML5The Fight Over HTML5
The Fight Over HTML5Mike Wilcox
 
The Fight Over HTML5
The Fight Over HTML5The Fight Over HTML5
The Fight Over HTML5Mike 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 DeveloperMike Wilcox
 
The History of HTML5
The History of HTML5The History of HTML5
The History of HTML5Mike Wilcox
 

Mehr von 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
 

Kürzlich hochgeladen

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 

Kürzlich hochgeladen (20)

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 

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

Hinweis der Redaktion