SlideShare uma empresa Scribd logo
1 de 16
Baixar para ler offline
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);
                });
            }
      });
});

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Java arrays
Java arraysJava arrays
Java arrays
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
TypeScript VS JavaScript.pptx
TypeScript VS JavaScript.pptxTypeScript VS JavaScript.pptx
TypeScript VS JavaScript.pptx
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Types of methods in python
Types of methods in pythonTypes of methods in python
Types of methods in python
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basics
 
Web api
Web apiWeb api
Web api
 
Generics
GenericsGenerics
Generics
 

Semelhante a 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
 

Semelhante a 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
 

Último

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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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, ...
 
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
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
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...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

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