SlideShare une entreprise Scribd logo
1  sur  16
Télécharger pour lire hors ligne
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);
                });
            }
      });
});

Contenu connexe

Tendances

Tendances (20)

JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
Javascript
JavascriptJavascript
Javascript
 
Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipes
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Asp.net MVC training session
Asp.net MVC training sessionAsp.net MVC training session
Asp.net MVC training session
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
Express js
Express jsExpress js
Express js
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Angular components
Angular componentsAngular components
Angular components
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
Angular Observables & RxJS Introduction
Angular Observables & RxJS IntroductionAngular Observables & RxJS Introduction
Angular Observables & RxJS Introduction
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 

Similaire à JavaScript Execution Context

Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 
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
 

Similaire à 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
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
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
 

Dernier

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

Dernier (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

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); }); } }); });