SlideShare a Scribd company logo
1 of 27
The global object,
execution contexts &
closures
in
JavaScript
© Hans de Rooij
hdr.is-a-geek.com
Introduction
● Even after studying JavaScript for quite some
time three subjects remained elusive;
– the global object
– execution contexts &
– closures
● Then I happened to stumble upon a great
article by Dmitry Soshnikov
– Read the full article (http://bit.ly/1jDSFBh)
Why these slides?
● Dmitri's article is great but, in my modest
opinion, can be challenging because of the
high information density
● Furthermore, although the article contains
illustrations, I wanted more visual aides to
help me understand the concepts at hand
● So this presentation is all about how I read
the article and the Visio diagrams I created
to help me understand the JavaScript global
object, execution contexts and closures
JavaScript global object
● Dimitri provides the following definition for the
JavaScript global object;
The global object is the object which is created
before entering any execution context; this object
exists in a single copy, its properties are
accessible from any place in the program and the
life cycle of the global object ends when the
program ends
JavaScript global object
● Global object build-ins;
– global properties like undefined, Infinity and NaN
– global functions like isNaN(), parseInt() and eval()
– constructor functions like Object(), Array(), ...
– global singleton objects like Math and JSON
● The properties of the global object are not
reserved words but deserve to be treated as
such
JavaScript global object
● To retrieve a reference to the global object it's
always possible to use;
var global = (function() {return this;})();
● In browsers the object reference window is
the global object's delegate
● The following is true in the global context;
– isNaN === global.isNaN; (only after above assignment)
– isNaN === window.isNaN; (when run in a browser)
– isNaN === this.isNaN; (more on this, pun intended, later)
JavaScript execution context
● Every bit of JavaScript code is evaluated in an
execution context (EC for short)
● When the JS engine begins executing code, it
first enters the global execution context
● An EC has a set of properties to facilitate the
processing of its associated code
JavaScript execution context
● Elements of a JavaScript program runtime
JavaScript execution context
● Program runtime in case a function f() is
declared besides variable a
● Please note that, in this example, function f()
is not invoked!
* For more on function
declaration click here
JavaScript execution context
● There are two main types of JavaScript code;
– global code
– function code
● There is only one global context and may be
many instances of function contexts
● Every function invocation creates a separate
function execution context
JavaScript EC stack
● JavaScript program runtime can be visualized
as an execution context stack
● The top of the stack is the active context
JavaScript EC stack
● Program runtime immediately before function
invocation
JavaScript EC stack
● Program runtime while processing the code of
function f
JavaScript scope chain
● A scope chain is a list of objects which is
searched for identifiers that appear in code
● A variable object is a container of data
associated with the execution context
● In the global context the variable object is the
global object
● An activation object is created every time a
function is invoked
● The activation object is then used as the
variable object of the function context
JavaScript scope chain
● Resolving variable b in function f
JavaScript scope chain
● Resolving variable a in function f
JavaScript closures
● Closures are functions that have access to
variables from another function's scope
● In JavaScript closures are most often created
using nested functions
● If a nested function (example ret_f) is returned
from another function (example times_x) and
references variables from the parent context
(example var x) then this function retains a
reference to the parent's scope as it was at
the moment of instantiation of the function
JavaScript closures
JavaScript closures
JavaScript closures
JavaScript closures
JavaScript closures
JavaScript closures
Addendum: this
● The value of this is a property of the
execution context
● The value of this is set when entering an
execution context and cannot be changed
● The value of this never participates in the
identifier resolution process
– i.e. a this reference in JS code is immediately
resolved as a property of the active execution
context without a scope chain lookup
Addendum: this
● In the global context this refers to the global
object
● In a function context;
– the this value may be different with every single
function call
– the this value of an EC depends on the form of
the call expression
– In strict mode functions invoked as functions
(rather than as methods) always have a this
value of undefined
Addendum: this
var global = (function() {return this;})();
var a = 3;
var obj_1 = {a: 4, f: func};
var obj_2 = {a: 5};
function sThis(tp) {
if(tp === global) {return "Global object";}
else if(tp === obj_1) {return "Object obj_1";}
else if(tp === obj_2) {return "Object obj_2";}
else {return "Hmmm ... ";}
}
function func() {
alert(this.a + ", " + sThis(this));
}
func(); //3, Global object
obj_1.f(); //4, Object obj_1
func.call(obj_2); //5, Object obj_2
Conclusion
● I highly recommend reading Dmitry Soshnikov
article on the global object, execution contexts,
closures and this
● This article helped me understand these
concepts and, as a result, improved my
JavaScript skills in general
● I hope this presentation and the included Visio
diagrams help you with your study of the above
mentioned topics
© Hans de Rooij hdr.is-a-geek.com

More Related Content

What's hot

Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptDhruvin Shah
 
Qtp training session IV
Qtp training session IVQtp training session IV
Qtp training session IVAisha Mazhar
 
JavaScript Beyond jQuery
JavaScript Beyond jQueryJavaScript Beyond jQuery
JavaScript Beyond jQueryBobby Bryant
 
Declarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetationDeclarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetationOm Shankar
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Devang Garach
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and DestructorsKeyur Vadodariya
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in JavascriptKnoldus Inc.
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartChen Fisher
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?Squareboat
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesHùng Nguyễn Huy
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaKnoldus Inc.
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classesVijay Kalyan
 
Functional programming and ruby in functional style
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional styleNiranjan Sarade
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Groovy / comparison with java
Groovy / comparison with javaGroovy / comparison with java
Groovy / comparison with javaLiviu Tudor
 

What's hot (20)

Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Qtp training session IV
Qtp training session IVQtp training session IV
Qtp training session IV
 
JavaScript Beyond jQuery
JavaScript Beyond jQueryJavaScript Beyond jQuery
JavaScript Beyond jQuery
 
Declarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetationDeclarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetation
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6
 
JavaScript operators
JavaScript operatorsJavaScript operators
JavaScript operators
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classes
 
Callback Function
Callback FunctionCallback Function
Callback Function
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript Programming
 
Functional programming and ruby in functional style
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional style
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Groovy / comparison with java
Groovy / comparison with javaGroovy / comparison with java
Groovy / comparison with java
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 

Similar to JavaScript global object, execution contexts & closures

Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
Object oriented java script
Object oriented java scriptObject oriented java script
Object oriented java scriptvivek p s
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming PrimerMike Wilcox
 
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...Codemotion
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functionsSwapnil Yadav
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsNir Noy
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webpjcozzi
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into JavascriptMassimo Franciosa
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp DeveloperSarvesh Kushwaha
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to javaSadhanaParameswaran
 

Similar to JavaScript global object, execution contexts & closures (20)

[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Object oriented java script
Object oriented java scriptObject oriented java script
Object oriented java script
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming Primer
 
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
 
React native
React nativeReact native
React native
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open web
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into Javascript
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
 

Recently uploaded

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 

Recently uploaded (20)

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 

JavaScript global object, execution contexts & closures

  • 1. The global object, execution contexts & closures in JavaScript © Hans de Rooij hdr.is-a-geek.com
  • 2. Introduction ● Even after studying JavaScript for quite some time three subjects remained elusive; – the global object – execution contexts & – closures ● Then I happened to stumble upon a great article by Dmitry Soshnikov – Read the full article (http://bit.ly/1jDSFBh)
  • 3. Why these slides? ● Dmitri's article is great but, in my modest opinion, can be challenging because of the high information density ● Furthermore, although the article contains illustrations, I wanted more visual aides to help me understand the concepts at hand ● So this presentation is all about how I read the article and the Visio diagrams I created to help me understand the JavaScript global object, execution contexts and closures
  • 4. JavaScript global object ● Dimitri provides the following definition for the JavaScript global object; The global object is the object which is created before entering any execution context; this object exists in a single copy, its properties are accessible from any place in the program and the life cycle of the global object ends when the program ends
  • 5. JavaScript global object ● Global object build-ins; – global properties like undefined, Infinity and NaN – global functions like isNaN(), parseInt() and eval() – constructor functions like Object(), Array(), ... – global singleton objects like Math and JSON ● The properties of the global object are not reserved words but deserve to be treated as such
  • 6. JavaScript global object ● To retrieve a reference to the global object it's always possible to use; var global = (function() {return this;})(); ● In browsers the object reference window is the global object's delegate ● The following is true in the global context; – isNaN === global.isNaN; (only after above assignment) – isNaN === window.isNaN; (when run in a browser) – isNaN === this.isNaN; (more on this, pun intended, later)
  • 7. JavaScript execution context ● Every bit of JavaScript code is evaluated in an execution context (EC for short) ● When the JS engine begins executing code, it first enters the global execution context ● An EC has a set of properties to facilitate the processing of its associated code
  • 8. JavaScript execution context ● Elements of a JavaScript program runtime
  • 9. JavaScript execution context ● Program runtime in case a function f() is declared besides variable a ● Please note that, in this example, function f() is not invoked! * For more on function declaration click here
  • 10. JavaScript execution context ● There are two main types of JavaScript code; – global code – function code ● There is only one global context and may be many instances of function contexts ● Every function invocation creates a separate function execution context
  • 11. JavaScript EC stack ● JavaScript program runtime can be visualized as an execution context stack ● The top of the stack is the active context
  • 12. JavaScript EC stack ● Program runtime immediately before function invocation
  • 13. JavaScript EC stack ● Program runtime while processing the code of function f
  • 14. JavaScript scope chain ● A scope chain is a list of objects which is searched for identifiers that appear in code ● A variable object is a container of data associated with the execution context ● In the global context the variable object is the global object ● An activation object is created every time a function is invoked ● The activation object is then used as the variable object of the function context
  • 15. JavaScript scope chain ● Resolving variable b in function f
  • 16. JavaScript scope chain ● Resolving variable a in function f
  • 17. JavaScript closures ● Closures are functions that have access to variables from another function's scope ● In JavaScript closures are most often created using nested functions ● If a nested function (example ret_f) is returned from another function (example times_x) and references variables from the parent context (example var x) then this function retains a reference to the parent's scope as it was at the moment of instantiation of the function
  • 24. Addendum: this ● The value of this is a property of the execution context ● The value of this is set when entering an execution context and cannot be changed ● The value of this never participates in the identifier resolution process – i.e. a this reference in JS code is immediately resolved as a property of the active execution context without a scope chain lookup
  • 25. Addendum: this ● In the global context this refers to the global object ● In a function context; – the this value may be different with every single function call – the this value of an EC depends on the form of the call expression – In strict mode functions invoked as functions (rather than as methods) always have a this value of undefined
  • 26. Addendum: this var global = (function() {return this;})(); var a = 3; var obj_1 = {a: 4, f: func}; var obj_2 = {a: 5}; function sThis(tp) { if(tp === global) {return "Global object";} else if(tp === obj_1) {return "Object obj_1";} else if(tp === obj_2) {return "Object obj_2";} else {return "Hmmm ... ";} } function func() { alert(this.a + ", " + sThis(this)); } func(); //3, Global object obj_1.f(); //4, Object obj_1 func.call(obj_2); //5, Object obj_2
  • 27. Conclusion ● I highly recommend reading Dmitry Soshnikov article on the global object, execution contexts, closures and this ● This article helped me understand these concepts and, as a result, improved my JavaScript skills in general ● I hope this presentation and the included Visio diagrams help you with your study of the above mentioned topics © Hans de Rooij hdr.is-a-geek.com