SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
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);
                });
            }
      });
});

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular ExpressionMasudul Haque
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#foreverredpb
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptionsmyrajendra
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency InjectionNir Kaufman
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?FITC
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom ManipulationMohammed Arif
 
Java script errors & exceptions handling
Java script  errors & exceptions handlingJava script  errors & exceptions handling
Java script errors & exceptions handlingAbhishekMondal42
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional StatementsMarlon Jamera
 

Was ist angesagt? (20)

Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
Java script errors & exceptions handling
Java script  errors & exceptions handlingJava script  errors & exceptions handling
Java script errors & exceptions handling
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional Statements
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 

Ähnlich wie 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 mastersAra Pehlivanian
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr 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-CNissan Tsafrir
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationIvan 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 NodeJSAdam L Barrett
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming PrimerMike Wilcox
 

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

Kürzlich hochgeladen

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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 WorkerThousandEyes
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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...Martijn de Jong
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 

Kürzlich hochgeladen (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

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