SlideShare a Scribd company logo
1 of 20
Download to read offline
Scoping and functions in
Javascript
 Aditya Gaur         Mentor: Apurba Nath
Why Scope?
   Controls the visibility of variables and
    parameters

   A programmer should know about scope to
    prevent naming collisions and ambiguity
Why Scope in Javascript?
   Javascript is NOT “s ome othe r la ngua ge ”

   Unlike other languages like C, C++,
    Javascript does not support bloc k le ve l
    s c ope

   Supports function level scope
Block level scope ?

        var a =10 ;      Output 20
        if(true){
           var a = 20;
        }
        alert(a);


        var a =10 ;      Output 10
        function
        randomFunc(){
           var a = 20;
        }
        randomFunc();
        alert(a);
Declaration and Definition

          var someVar = 10;



            is broken into


        var someVar=undefined;

        someVar =10;
Declaration and Definition

      function someFunc(){
          //some random statements
          var aVar = 10;
          //some more random statements
      }

            is converted to
      function someFunc(){
          var aVar = undefined
          //some random statements
          aVar = 10;
          //some more random statements
      }
The var

      function Dummy(){                          Output: Error- privateProperty is not
         var privateProperty = 10;               defined
      }
      alert (privateProperty);




      function Dummy(){                          Output: 10
         isItPrivate = 10;
      }
      alert(isItPrivate);

So what's happening? Actually the keyword var defines the scope of the variable. If
we don't give the keyword var then it is assigned to the window object
The eval function

eval("var a=10");                   Output: 10
alert(a);



function someFunc(){                Output: 10
   eval("var a=10");                         'a' is not defined
   alert(a);
}
someFunc();
alert(a);


Variables declared in the eval have the scope in which they are
called.
this is tricky
   It is one of the most important concept
    to grasp in javascript
   Its value depends in the way the function
    has been called.
   A function can be called in the following
    ways:
    –   As a method
    –   As function invocation
    –   As a constructor
    –   In apply invocation
1. Function as a method

var aVar=10;                Output: 40
var obj= {
    aVar: 40,
   show: function(){
      alert(this.aVar);
   }
};
obj.show();



this is bound to the object from which the method is
invoked.
2. function invocation

var aVar=10;                 Output: 10
function someFunc(){
  var aVar =40;
  alert(this.aVar);
}
someFunc();


Here the value of this is bound to the global object.
3. function as a constructor

 function Dummy(){                               Output: undefined
    var privateProperty = 10;
 }
 var dummyObject = new Dummy();
 alert(dummyObject.privateProperty);


function Dummy(){                                 Output: 10
   this.publicProperty = 10;
}
var dummyObject = new Dummy();
alert(dummyObject.publicProperty);


this is bound to the new object being created so it is accessible through the
object.
Privileged method

   function Dummy() {
      var privateProperty = 10;
      this.privilegedMethod = function() {
         return privateProperty;
      };
   }
   var dummyObject = new Dummy();
   alert(dummyObject.privilegedMethod());
4. function in apply invocation

    var obj = { x: 15 };
     function dummy(message)
    {
       alert(message);
       alert(this.x);
    }
    dummy.apply(obj, ["invoking dummy through apply"]);

    Output: invoking dummy through apply
           15




Here the value of this is bound to the scope passed as the first argument in the
apply function
A catch

function Dummy()
{
   return function (){
     alert (this);
  }();
}
var dummyObject = new Dummy();


Here this refers to the global object. Why?
The anonymous function here is executed immediately thus it is just like the
function invocation and in function invocation this refers to the global window
object
A fix

 function Dummy()
 {
   var that = this;
       return function (){
         alert (that);
   }();
 }
 var dummyObject = new Dummy();



Now we have the correct behaviour. This is possible because javascript
supports function closure.
Current and Future Work
   Working on
     – JSDocs – for the documentation
     – Integrated JSdocs in the build of the
       mVisualizer
   For unit testing would work either on
     – JSUnit
     – YUI test
Current and Future Work
References
   Javascript: the good parts by Douglas
    Crockford
   YUI theater videos by Douglas Crockford
Thank You

More Related Content

What's hot

Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ ConstructorSomenath Mukhopadhyay
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014DA-14
 
Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)Anna Khabibullina
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaHackBulgaria
 
C++ exception handling
C++ exception handlingC++ exception handling
C++ exception handlingRay Song
 
EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++Prof Ansari
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15Kumar
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляSergey Platonov
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsZohar Arad
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2ppd1961
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 
The Future of JavaScript (Ajax Exp '07)
The Future of JavaScript (Ajax Exp '07)The Future of JavaScript (Ajax Exp '07)
The Future of JavaScript (Ajax Exp '07)jeresig
 
Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCSwift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCTomohiro Kumagai
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations DVClub
 
N Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeN Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeAnton Kulyk
 
soscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profitsoscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profithanbeom Park
 

What's hot (20)

Lecture04
Lecture04Lecture04
Lecture04
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014
 
Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)
 
Exceptions in c++
Exceptions in c++Exceptions in c++
Exceptions in c++
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
 
C++ exception handling
C++ exception handlingC++ exception handling
C++ exception handling
 
EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2
 
Exception handling
Exception handlingException handling
Exception handling
 
The Future of JavaScript (Ajax Exp '07)
The Future of JavaScript (Ajax Exp '07)The Future of JavaScript (Ajax Exp '07)
The Future of JavaScript (Ajax Exp '07)
 
Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCSwift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDC
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
 
N Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeN Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React Native
 
soscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profitsoscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profit
 

Similar to Javascript scoping

JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution ContextJuan Medina
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS a_sharif
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !Gaurav Behere
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence Svekis ✔
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
JavaScript and AJAX
JavaScript and AJAXJavaScript and AJAX
JavaScript and AJAXFrane Bandov
 
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
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript Dhananjay Kumar
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 

Similar to Javascript scoping (20)

Javascript
JavascriptJavascript
Javascript
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
Side effects-con-redux
Side effects-con-reduxSide effects-con-redux
Side effects-con-redux
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
Closures
ClosuresClosures
Closures
 
JavaScript and AJAX
JavaScript and AJAXJavaScript and AJAX
JavaScript and AJAX
 
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
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 

Recently uploaded

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
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...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

Javascript scoping

  • 1. Scoping and functions in Javascript Aditya Gaur Mentor: Apurba Nath
  • 2. Why Scope?  Controls the visibility of variables and parameters  A programmer should know about scope to prevent naming collisions and ambiguity
  • 3. Why Scope in Javascript?  Javascript is NOT “s ome othe r la ngua ge ”  Unlike other languages like C, C++, Javascript does not support bloc k le ve l s c ope  Supports function level scope
  • 4. Block level scope ? var a =10 ; Output 20 if(true){ var a = 20; } alert(a); var a =10 ; Output 10 function randomFunc(){ var a = 20; } randomFunc(); alert(a);
  • 5. Declaration and Definition var someVar = 10; is broken into var someVar=undefined; someVar =10;
  • 6. Declaration and Definition function someFunc(){ //some random statements var aVar = 10; //some more random statements } is converted to function someFunc(){ var aVar = undefined //some random statements aVar = 10; //some more random statements }
  • 7. The var function Dummy(){ Output: Error- privateProperty is not var privateProperty = 10; defined } alert (privateProperty); function Dummy(){ Output: 10 isItPrivate = 10; } alert(isItPrivate); So what's happening? Actually the keyword var defines the scope of the variable. If we don't give the keyword var then it is assigned to the window object
  • 8. The eval function eval("var a=10"); Output: 10 alert(a); function someFunc(){ Output: 10 eval("var a=10"); 'a' is not defined alert(a); } someFunc(); alert(a); Variables declared in the eval have the scope in which they are called.
  • 9. this is tricky  It is one of the most important concept to grasp in javascript  Its value depends in the way the function has been called.  A function can be called in the following ways: – As a method – As function invocation – As a constructor – In apply invocation
  • 10. 1. Function as a method var aVar=10; Output: 40 var obj= { aVar: 40, show: function(){ alert(this.aVar); } }; obj.show(); this is bound to the object from which the method is invoked.
  • 11. 2. function invocation var aVar=10; Output: 10 function someFunc(){ var aVar =40; alert(this.aVar); } someFunc(); Here the value of this is bound to the global object.
  • 12. 3. function as a constructor function Dummy(){ Output: undefined var privateProperty = 10; } var dummyObject = new Dummy(); alert(dummyObject.privateProperty); function Dummy(){ Output: 10 this.publicProperty = 10; } var dummyObject = new Dummy(); alert(dummyObject.publicProperty); this is bound to the new object being created so it is accessible through the object.
  • 13. Privileged method function Dummy() { var privateProperty = 10; this.privilegedMethod = function() { return privateProperty; }; } var dummyObject = new Dummy(); alert(dummyObject.privilegedMethod());
  • 14. 4. function in apply invocation var obj = { x: 15 }; function dummy(message) { alert(message); alert(this.x); } dummy.apply(obj, ["invoking dummy through apply"]); Output: invoking dummy through apply 15 Here the value of this is bound to the scope passed as the first argument in the apply function
  • 15. A catch function Dummy() { return function (){ alert (this); }(); } var dummyObject = new Dummy(); Here this refers to the global object. Why? The anonymous function here is executed immediately thus it is just like the function invocation and in function invocation this refers to the global window object
  • 16. A fix function Dummy() { var that = this; return function (){ alert (that); }(); } var dummyObject = new Dummy(); Now we have the correct behaviour. This is possible because javascript supports function closure.
  • 17. Current and Future Work  Working on – JSDocs – for the documentation – Integrated JSdocs in the build of the mVisualizer  For unit testing would work either on – JSUnit – YUI test
  • 19. References  Javascript: the good parts by Douglas Crockford  YUI theater videos by Douglas Crockford