SlideShare a Scribd company logo
JavaScript
Execution Context (EC)
        Closures
     "this" keyword
 ...and other demons
Some key concepts

● JS is a high-level programming language
● Executed at runtime
● Weakly typed
● Prototype-based
   ○ Class-less
   ○ Inheritance through cloning of objects then...
   ○ Delegation from the prototype

var globant = {arg: 1500, uru: 150, col: 50};
var agency = {world: 1800};
agency.__proto__ = globant;
alert(agency.arg);
alert(agency.world);
What's going on here?
function outerFunc(externalArg) {
    var localVar = 100;

    function innerFunc(innerArg) {
        localVar += 100;
        return (externalArg + innerArg + localVar);
    }

    return innerFunc;
}

var globalVar = outerFunc(200);
alert(globalVar(300));
alert(globalVar(300));

globalVar = outerFunc(200);
alert(globalVar(300));
Execution Context Maxims

All the JS code runs within an   JS Code is encapsulated
Execution Context.               within a set of Objects &
                                 properties.



 Execute           code!
Execution Context Maxims

The default Execution Context   Each function( )
is the window Object.           invocation has an associated
                                Execution Context.
Execution Context Maxims

If a nested function( )is       When the control returns to
called a new EC is created      the original EC it is available
and the execution enters that   for garbage collection except
context until the               when we create a closure.
function( ) returns.



             Thus, running JavaScript code
                      generates a:
          Stack of Execution Contexts
Activation Object

● Execution Context creates an : Activation Object

  ○ Behaves as an JS Object with properties
  ○ But has NO prototype and cannot be referenced
  ○ Serves to store call( )arguments & var declarations
  ○ Let's not care about this



                                          Okay
Variable Instantiation

● Prepare the var, function(arg)declarations and
  arguments to be accessible during execution
   ○ var globant;
   ○ var rock = function(arg){ alert('rock')};
● Initially assigned null properties or 'undefined' values

● They become named properties of the
  var (Activation) Object

● The instantiated var will be interpreted against the scope of
  the current Execution Context


                                           Scope? Wait for it...
The Scope
● Each Execution Context has a Scope

● A Scope is an Activation Object
   ○ Part of the var Object

● Scopes can be chained by the JS interpreter

● The Scope chain is a native property of every
  function( )declaration
Variable Resolution

● Every time a var is called the interpreter will try to resolve it

● It resolves it against the Scope of the current EC

● It will continue upwards to the next EC until the window

● If it's not found it will return 'undefined'

● This is also a Scope chain
Textbook definition of Closures




        A "closure" is an expression (typically a
        function) that can have free variables
        together with an environment that binds
        those variables (that "closes" the expression).
Closures

If an Object (var) has no     Unless... we create a closure
remaining references once
the execution ends, it gets   ● A closure is the local
collected by the garbage        variables for a function -
collector                       kept alive after the function
                                has returned.

                              ● A closure is an Execution
                                Context which is not de-
                                allocated when the
                                function returns.
What's going on here? Closure!
function outerFunc(externalArg) {
    var localVar = 100;

    function innerFunc(innerArg) {
        localVar += 100;
        return (externalArg + innerArg + localVar);
    }

    return innerFunc;
}                                   outerFunc( ) returns a
                                    reference to innerFunc( )
var globalVar = outerFunc(200);     We declare a var that runs &
alert(globalVar(300));              holds whatever outerFunc( )
alert(globalVar(300));              returns

globalVar = outerFunc(200);         When we call globalVar(300)
alert(globalVar(300));              again, we still have access to local
                                    var defined in outerFunc( )
Another Closure example

function say778() {
    var num = 777;
    var sayAlert = function() {
        alert(num);
    }
    num++;
    return sayAlert;
}

var sayNumber = say778();
sayNumber();

alert(sayNumber);
The "this" keyword

● Gets assigned along every new Execution Context

● It always refers to the Object that the containing function(
  ) is a method of

function redColor() {
    this.color = 'red';
}

redColor();

alert(redColor.color);          //shows "undefined"
alert(window.color);            //shows "red"
Closures in jQuery
$(function() {
    var anchors = $('a');
    anchors.each(function(i, e) {
        var self = $(this);

            if($(this).text() !== 'Contact me') {
                $(this).click(function(e) {
                    var that = $(this);
                      that.css({'textDecoration' : 'underline'});
                      self.css({'color' : 'red'});
                      setTimeout(function(e) {
                          anchors
                          that.css({'color' : 'blue'});
                      }, 1000);
                });
            }
      });
});

More Related Content

What's hot

Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
Kevin Langley Jr.
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
Java script errors & exceptions handling
Java script  errors & exceptions handlingJava script  errors & exceptions handling
Java script errors & exceptions handling
AbhishekMondal42
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
Sonya Akter Rupa
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
Lovely Professional University
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
pcnmtutorials
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Selenium IDE LOCATORS
Selenium IDE LOCATORSSelenium IDE LOCATORS
Selenium IDE LOCATORS
Mindfire Solutions
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Edureka!
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
vite-en.pdf
vite-en.pdfvite-en.pdf
vite-en.pdf
ssuser65180a
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
Vishnu Suresh
 
Beyond Scala Lens
Beyond Scala LensBeyond Scala Lens
Beyond Scala Lens
Julien Truffaut
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
Arulalan T
 

What's hot (20)

Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Java script errors & exceptions handling
Java script  errors & exceptions handlingJava script  errors & exceptions handling
Java script errors & exceptions handling
 
Spring framework core
Spring framework coreSpring framework core
Spring framework core
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Selenium IDE LOCATORS
Selenium IDE LOCATORSSelenium IDE LOCATORS
Selenium IDE LOCATORS
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
Javascript event handler
Javascript event handlerJavascript event handler
Javascript event handler
 
vite-en.pdf
vite-en.pdfvite-en.pdf
vite-en.pdf
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
Beyond Scala Lens
Beyond Scala LensBeyond Scala Lens
Beyond Scala Lens
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 

Similar to JavaScript Execution Context

Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
Piotr Pelczar
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
Nissan Tsafrir
 
Javascript
JavascriptJavascript
Javascript
Gita Kriz
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
Zsolt Mészárovics
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
Chalermpon Areepong
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
Ivan Dolgushin
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
Underscore and Backbone Models
Underscore and Backbone ModelsUnderscore and Backbone Models
Underscore and Backbone Models
Kentucky JavaScript Users Group
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming Primer
Mike Wilcox
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
scalaconfjp
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
Paweł Dorofiejczyk
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
Shaul Rosenzwieg
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 

Similar to JavaScript Execution Context (20)

Javascript
JavascriptJavascript
Javascript
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
 
Javascript
JavascriptJavascript
Javascript
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Underscore and Backbone Models
Underscore and Backbone ModelsUnderscore and Backbone Models
Underscore and Backbone Models
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming Primer
 
Java scriptconfusingbits
Java scriptconfusingbitsJava scriptconfusingbits
Java scriptconfusingbits
 
Java scriptconfusingbits
Java scriptconfusingbitsJava scriptconfusingbits
Java scriptconfusingbits
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 

Recently uploaded

FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 

JavaScript Execution Context

  • 1. JavaScript Execution Context (EC) Closures "this" keyword ...and other demons
  • 2. Some key concepts ● JS is a high-level programming language ● Executed at runtime ● Weakly typed ● Prototype-based ○ Class-less ○ Inheritance through cloning of objects then... ○ Delegation from the prototype var globant = {arg: 1500, uru: 150, col: 50}; var agency = {world: 1800}; agency.__proto__ = globant; alert(agency.arg); alert(agency.world);
  • 3. What's going on here? function outerFunc(externalArg) { var localVar = 100; function innerFunc(innerArg) { localVar += 100; return (externalArg + innerArg + localVar); } return innerFunc; } var globalVar = outerFunc(200); alert(globalVar(300)); alert(globalVar(300)); globalVar = outerFunc(200); alert(globalVar(300));
  • 4. Execution Context Maxims All the JS code runs within an JS Code is encapsulated Execution Context. within a set of Objects & properties. Execute code!
  • 5. Execution Context Maxims The default Execution Context Each function( ) is the window Object. invocation has an associated Execution Context.
  • 6. Execution Context Maxims If a nested function( )is When the control returns to called a new EC is created the original EC it is available and the execution enters that for garbage collection except context until the when we create a closure. function( ) returns. Thus, running JavaScript code generates a: Stack of Execution Contexts
  • 7. Activation Object ● Execution Context creates an : Activation Object ○ Behaves as an JS Object with properties ○ But has NO prototype and cannot be referenced ○ Serves to store call( )arguments & var declarations ○ Let's not care about this Okay
  • 8. Variable Instantiation ● Prepare the var, function(arg)declarations and arguments to be accessible during execution ○ var globant; ○ var rock = function(arg){ alert('rock')}; ● Initially assigned null properties or 'undefined' values ● They become named properties of the var (Activation) Object ● The instantiated var will be interpreted against the scope of the current Execution Context Scope? Wait for it...
  • 9. The Scope ● Each Execution Context has a Scope ● A Scope is an Activation Object ○ Part of the var Object ● Scopes can be chained by the JS interpreter ● The Scope chain is a native property of every function( )declaration
  • 10. Variable Resolution ● Every time a var is called the interpreter will try to resolve it ● It resolves it against the Scope of the current EC ● It will continue upwards to the next EC until the window ● If it's not found it will return 'undefined' ● This is also a Scope chain
  • 11. Textbook definition of Closures A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
  • 12. Closures If an Object (var) has no Unless... we create a closure remaining references once the execution ends, it gets ● A closure is the local collected by the garbage variables for a function - collector kept alive after the function has returned. ● A closure is an Execution Context which is not de- allocated when the function returns.
  • 13. What's going on here? Closure! function outerFunc(externalArg) { var localVar = 100; function innerFunc(innerArg) { localVar += 100; return (externalArg + innerArg + localVar); } return innerFunc; } outerFunc( ) returns a reference to innerFunc( ) var globalVar = outerFunc(200); We declare a var that runs & alert(globalVar(300)); holds whatever outerFunc( ) alert(globalVar(300)); returns globalVar = outerFunc(200); When we call globalVar(300) alert(globalVar(300)); again, we still have access to local var defined in outerFunc( )
  • 14. Another Closure example function say778() { var num = 777; var sayAlert = function() { alert(num); } num++; return sayAlert; } var sayNumber = say778(); sayNumber(); alert(sayNumber);
  • 15. The "this" keyword ● Gets assigned along every new Execution Context ● It always refers to the Object that the containing function( ) is a method of function redColor() { this.color = 'red'; } redColor(); alert(redColor.color); //shows "undefined" alert(window.color); //shows "red"
  • 16. Closures in jQuery $(function() { var anchors = $('a'); anchors.each(function(i, e) { var self = $(this); if($(this).text() !== 'Contact me') { $(this).click(function(e) { var that = $(this); that.css({'textDecoration' : 'underline'}); self.css({'color' : 'red'}); setTimeout(function(e) { anchors that.css({'color' : 'blue'}); }, 1000); }); } }); });