SlideShare a Scribd company logo
1 of 37
Function Works in
    JavaScript
Funny Code
alert(run(10)); //?
var run = true;
alert(run);        //?
function run(n){
  return n x n;
}
It’s only “Hoisted”?
Very^32 Important
       Function

• Definition(Expression, Declaration)


• Execution(invoke)


• Creation
         (new) - not yet :(
Associated with
        Function
• this
• execution context
• scope(scope chain)
• closure
Let’s Go!
Define function

• Function Expression
• Function Declaration
• Function Constructor
Function Expression
• Function Expression defines a function
  as a part of a large expression syntax

• Functions defined via Functions
  Expressions can be named or
  anonymous

• Function Expressions must not start with
  “function”
ECMA 5(13.0)
               defines the syntax as



function Identifieropt(FormalParametersListopt) { FunctionBody }
Function Expression
       anonymous function



  var foo = function(x, y) {
     return x + y;
  }

  sum(20, 30); //return 50
Function Expression
         named function



  var foo = function sum(x, y) {
     return x + y;
  }

  sum(20, 30); //return 50
Function Expression
       self invoking function



  (function sum(x, y) {
     return x + y;
  })(20,30);

  sum(20, 30); //return 50
Function Declaration
• Function Declaration defines a named function
  variable without requiring variable assignment

• Function Declarations occur as standalone
  constructs and cannot be nested within non-
  function blocks

• Just as Variable Declarations must start with
  “var”, Function Declarations must begin with
  “function”
ECMA 5(13.0)
               defines the syntax as



function Identifier(FormalParametersListopt) { FunctionBody }
Function Declaration
         named function



  function sum(x, y) {
     return x + y;
  }

  sum(20, 30); //return 50
Function Constructor

• When Function is called as part of a
  new expression, it is a constructor

• It initialize the newly created object
ECMA 5(15.3)
defines the syntax as



Function(p1, p2, ... ,pn, body);
Function Constructor

var foo = new Function(“x”, “y”,
”return x + y;”);

foo(20, 30); //return 50
What’s happen?
                                                                        Global
activation object                                                function outerFunc;
      assign arguments        outerFunc context

                         outerFunc Activation Object
                                                                 arguments Object
variable instantiation              arguments

   local variable definition           local

                                    innerFunc                         innerFunc
                                                                function instantiation
                                     [scope]

function instantiation
  nested function definition                    assign [scope]
                                                  assign this keyword
Function Execution
function outerFunc() {             Global

  var local = 3;            function outerFunc;


  function innerFunc() {           [scope]
    return local++;         Activation Object for
                             function outerFunc
  };                              local = 3,
                             function innerFunc
  return innerFunc();
}                                  [scope]

alert(outerFunc()); //”4”   Activation Object for
                             function innerFunc
Function Execution
                                 global context

function outerFunc() {                outerFunc


  var local = 3;               outerFunc context

  function innerFunc() {    outerFunc Activation Object
                                         local
    return local++;                    innerFunc

  };                                    [scope]


  return innerFunc();           innerFunc Object

}                              innerFunc context

alert(outerFunc()); //”4”   innerFunc Activation Object
                                        [scope]
Function Execution
                                 global context

function outerFunc() {                outerFunc


  var local = 3;               outerFunc context

  function innerFunc() {    outerFunc Activation Object
                                         local
    return local++;                    innerFunc

  };                                    [scope]


  return innerFunc();           innerFunc Object

}                              innerFunc context

alert(outerFunc()); //”4”   innerFunc Activation Object
                                        [scope]
Function Execution
                                 global context

function outerFunc() {                outerFunc


  var local = 3;               outerFunc context

  function innerFunc() {    outerFunc Activation Object
                                         local
    return local++;                    innerFunc

  };                                    [scope]


  return innerFunc();           innerFunc Object

}                              innerFunc context

alert(outerFunc()); //”4”   innerFunc Activation Object
                                        [scope]
Function Execution
                                 global context

function outerFunc() {                outerFunc


  var local = 3;               outerFunc context

  function innerFunc() {    outerFunc Activation Object
                                         local
    return local++;                    innerFunc

  };                                    [scope]


  return innerFunc();           innerFunc Object

}                              innerFunc context

alert(outerFunc()); //”4”   innerFunc Activation Object
                                        [scope]
Function Execution
                                 global context

function outerFunc() {                outerFunc


  var local = 3;               outerFunc context

  function innerFunc() {    outerFunc Activation Object
                                         local
    return local++;                    innerFunc

  };                                    [scope]


  return innerFunc();           innerFunc Object

}                              innerFunc context

alert(outerFunc()); //”4”   innerFunc Activation Object
                                        [scope]
Function Execution
                                 global context

function outerFunc() {                outerFunc


  var local = 3;               outerFunc context

  function innerFunc() {    outerFunc Activation Object
                                         local
    return local++;                    innerFunc

  };                                 [scope] = this


  return innerFunc();           innerFunc Object

}                              innerFunc context

alert(outerFunc()); //”4”   innerFunc Activation Object
                                        [scope]
Function Execution
                                 global context

function outerFunc() {                outerFunc


  var local = 3;               outerFunc context

  function innerFunc() {    outerFunc Activation Object
                                         local
    return local++;                    innerFunc

  };                                 [scope] = this


  return innerFunc();           innerFunc Object

}                              innerFunc context

alert(outerFunc()); //”4”   innerFunc Activation Object
                                        [scope]
Function Execution
                                 global context

function outerFunc() {                outerFunc


  var local = 3;               outerFunc context

  function innerFunc() {    outerFunc Activation Object
                                         local
    return local++;                    innerFunc

  };                                 [scope] = this


  return innerFunc();           innerFunc Object

}                              innerFunc context

alert(outerFunc()); //”4”   innerFunc Activation Object
                                        [scope]
Function Execution
                                 global context

function outerFunc() {                outerFunc


  var local = 3;               outerFunc context

  function innerFunc() {    outerFunc Activation Object
                                         local
    return local++;                    innerFunc

  };                                 [scope] = this


  return innerFunc();           innerFunc Object

}                              innerFunc context

alert(outerFunc()); //”4”   innerFunc Activation Object
                                  [scope] = outerFunc
Function Execution
                                 global context

function outerFunc() {                outerFunc


  var local = 3;               outerFunc context

  function innerFunc() {    outerFunc Activation Object
                                         local
    return local++;                    innerFunc

  };                                 [scope] = this


  return innerFunc();           innerFunc Object

}                              innerFunc context

alert(outerFunc()); //”4”   innerFunc Activation Object
                                  [scope] = outerFunc
Function Execution
            Summary I
•
    •           (Activation Object)

    •   arguments            length, callee                       .

    •             arguments
            arguments

    •           (Scope)

        •                                     .

        •                                +            ‘[scope]’
                                                  .

    •           ,


    •               ‘this’                .
Function Execution
           Summary II
•
    •
            .

    •
                      .

    •
            .(            .)

•
    •
                 .
Function Instantiation
•
    •
        .

    •
              .

    •
            ‘[scope]’   .
Top level Function
var x = 3, y = 4;                Global
function outerFunc(i) {       x = 3; y = 4;
                           function outerFn;
  var x = true;
  y = y + i;
  alert(x);
                          Activation Object for
}                           function outerFn
                             i = 5; x = true;
alert(outerFunc(5));
                                       Scope chain at execution
                                       of outerFn(5)
Scope Chain diagram

   [scope]                         Global




      [scope]                ...




             [scope]   [scope]
Variable Resolution
var local = 3;
function f4() {
  function f3() {                                 local is
                                                   here
    function f2() {
      function f1() {   f1.[scope]    Global
        return local;
      }
      return f1();
                        f2.[scope]      ...
    }
    return f2();
  }
  return f3();          f3.[scope]   f4.[scope]
}
alert(f4());
Scope Chain Point
•               (Function Object)                ‘[scope]‘
                                         .

•   ‘[scope]’                                .

•                          , ‘[scope]’
      ‘                ’            .

•                                                                .

•         ‘[scope]’
                                                             .

More Related Content

What's hot

Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpen Gurukul
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes
 
NIO.2, the I/O API for the future
NIO.2, the I/O API for the futureNIO.2, the I/O API for the future
NIO.2, the I/O API for the futureMasoud Kalali
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
Groovy 1.8の新機能について
Groovy 1.8の新機能についてGroovy 1.8の新機能について
Groovy 1.8の新機能についてUehara Junji
 
북스터디 디스커버리 Go 언어
북스터디 디스커버리 Go 언어북스터디 디스커버리 Go 언어
북스터디 디스커버리 Go 언어동규 이
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014Fantix King 王川
 
Java nio ( new io )
Java nio ( new io )Java nio ( new io )
Java nio ( new io )Jemin Patel
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Uehara Junji
 
Python-GTK
Python-GTKPython-GTK
Python-GTKYuren Ju
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEUehara Junji
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the pointseanmcq
 
The Ring programming language version 1.5.4 book - Part 78 of 185
The Ring programming language version 1.5.4 book - Part 78 of 185The Ring programming language version 1.5.4 book - Part 78 of 185
The Ring programming language version 1.5.4 book - Part 78 of 185Mahmoud Samir Fayed
 
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Martijn Verburg
 

What's hot (20)

Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
Java NIO.2
Java NIO.2Java NIO.2
Java NIO.2
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
NIO.2, the I/O API for the future
NIO.2, the I/O API for the futureNIO.2, the I/O API for the future
NIO.2, the I/O API for the future
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Groovy 1.8の新機能について
Groovy 1.8の新機能についてGroovy 1.8の新機能について
Groovy 1.8の新機能について
 
북스터디 디스커버리 Go 언어
북스터디 디스커버리 Go 언어북스터디 디스커버리 Go 언어
북스터디 디스커버리 Go 언어
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
 
Java nio ( new io )
Java nio ( new io )Java nio ( new io )
Java nio ( new io )
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVE
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
 
Python modules
Python modulesPython modules
Python modules
 
The Ring programming language version 1.5.4 book - Part 78 of 185
The Ring programming language version 1.5.4 book - Part 78 of 185The Ring programming language version 1.5.4 book - Part 78 of 185
The Ring programming language version 1.5.4 book - Part 78 of 185
 
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2
 

Similar to Function work in JavaScript

Active Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVEActive Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVEkim.mens
 
Durable functions
Durable functionsDurable functions
Durable functions명신 김
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizenVytautas Butkus
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsNir Noy
 
Javascript Execution Context Flow
Javascript Execution Context FlowJavascript Execution Context Flow
Javascript Execution Context Flowkang taehun
 

Similar to Function work in JavaScript (11)

COM and DCOM
COM and DCOMCOM and DCOM
COM and DCOM
 
Active Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVEActive Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVE
 
Functions
FunctionsFunctions
Functions
 
AFPS_2011
AFPS_2011AFPS_2011
AFPS_2011
 
Durable functions
Durable functionsDurable functions
Durable functions
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizen
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Mattbrenner
MattbrennerMattbrenner
Mattbrenner
 
Javascript Execution Context Flow
Javascript Execution Context FlowJavascript Execution Context Flow
Javascript Execution Context Flow
 
Javascript talk
Javascript talkJavascript talk
Javascript talk
 

More from Rhio Kim

Javascript fatigue, 자바스크립트 피로
Javascript fatigue, 자바스크립트 피로Javascript fatigue, 자바스크립트 피로
Javascript fatigue, 자바스크립트 피로Rhio Kim
 
문서화에 날개를 달아주는 Flybook CLI
문서화에 날개를 달아주는 Flybook CLI문서화에 날개를 달아주는 Flybook CLI
문서화에 날개를 달아주는 Flybook CLIRhio Kim
 
나는 오픈소스로 화가가 되었다
나는 오픈소스로 화가가 되었다나는 오픈소스로 화가가 되었다
나는 오픈소스로 화가가 되었다Rhio Kim
 
Node.js 기반 정적 페이지 블로그 엔진, 하루프레스
Node.js 기반 정적 페이지 블로그 엔진, 하루프레스Node.js 기반 정적 페이지 블로그 엔진, 하루프레스
Node.js 기반 정적 페이지 블로그 엔진, 하루프레스Rhio Kim
 
우리가 모르는 노드로 할 수 있는 몇가지
우리가 모르는 노드로 할 수 있는 몇가지우리가 모르는 노드로 할 수 있는 몇가지
우리가 모르는 노드로 할 수 있는 몇가지Rhio Kim
 
Git Flow tutorial
Git Flow tutorialGit Flow tutorial
Git Flow tutorialRhio Kim
 
하루프레스
하루프레스하루프레스
하루프레스Rhio Kim
 
웹 소프트웨어 시대의 새로운 롤(role) 모델, 자바스크립트
웹 소프트웨어 시대의 새로운 롤(role) 모델, 자바스크립트웹 소프트웨어 시대의 새로운 롤(role) 모델, 자바스크립트
웹 소프트웨어 시대의 새로운 롤(role) 모델, 자바스크립트Rhio Kim
 
JavaScript History
JavaScript HistoryJavaScript History
JavaScript HistoryRhio Kim
 
2011 JavaScript Developer Generation
2011 JavaScript Developer Generation2011 JavaScript Developer Generation
2011 JavaScript Developer GenerationRhio Kim
 
Mobile appcelerator titanium
Mobile appcelerator titaniumMobile appcelerator titanium
Mobile appcelerator titaniumRhio Kim
 
Mobile appcelerator titanium
Mobile appcelerator titaniumMobile appcelerator titanium
Mobile appcelerator titaniumRhio Kim
 
Mobile appcelerator titanium
Mobile appcelerator titaniumMobile appcelerator titanium
Mobile appcelerator titaniumRhio Kim
 
CRUD Pattern in Ajax
CRUD Pattern in AjaxCRUD Pattern in Ajax
CRUD Pattern in AjaxRhio Kim
 

More from Rhio Kim (14)

Javascript fatigue, 자바스크립트 피로
Javascript fatigue, 자바스크립트 피로Javascript fatigue, 자바스크립트 피로
Javascript fatigue, 자바스크립트 피로
 
문서화에 날개를 달아주는 Flybook CLI
문서화에 날개를 달아주는 Flybook CLI문서화에 날개를 달아주는 Flybook CLI
문서화에 날개를 달아주는 Flybook CLI
 
나는 오픈소스로 화가가 되었다
나는 오픈소스로 화가가 되었다나는 오픈소스로 화가가 되었다
나는 오픈소스로 화가가 되었다
 
Node.js 기반 정적 페이지 블로그 엔진, 하루프레스
Node.js 기반 정적 페이지 블로그 엔진, 하루프레스Node.js 기반 정적 페이지 블로그 엔진, 하루프레스
Node.js 기반 정적 페이지 블로그 엔진, 하루프레스
 
우리가 모르는 노드로 할 수 있는 몇가지
우리가 모르는 노드로 할 수 있는 몇가지우리가 모르는 노드로 할 수 있는 몇가지
우리가 모르는 노드로 할 수 있는 몇가지
 
Git Flow tutorial
Git Flow tutorialGit Flow tutorial
Git Flow tutorial
 
하루프레스
하루프레스하루프레스
하루프레스
 
웹 소프트웨어 시대의 새로운 롤(role) 모델, 자바스크립트
웹 소프트웨어 시대의 새로운 롤(role) 모델, 자바스크립트웹 소프트웨어 시대의 새로운 롤(role) 모델, 자바스크립트
웹 소프트웨어 시대의 새로운 롤(role) 모델, 자바스크립트
 
JavaScript History
JavaScript HistoryJavaScript History
JavaScript History
 
2011 JavaScript Developer Generation
2011 JavaScript Developer Generation2011 JavaScript Developer Generation
2011 JavaScript Developer Generation
 
Mobile appcelerator titanium
Mobile appcelerator titaniumMobile appcelerator titanium
Mobile appcelerator titanium
 
Mobile appcelerator titanium
Mobile appcelerator titaniumMobile appcelerator titanium
Mobile appcelerator titanium
 
Mobile appcelerator titanium
Mobile appcelerator titaniumMobile appcelerator titanium
Mobile appcelerator titanium
 
CRUD Pattern in Ajax
CRUD Pattern in AjaxCRUD Pattern in Ajax
CRUD Pattern in Ajax
 

Recently uploaded

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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
 
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
 
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
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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
 
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
 
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
 
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
 
[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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
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
 
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
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
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
 
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
 
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...
 
[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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

Function work in JavaScript

  • 1. Function Works in JavaScript
  • 2. Funny Code alert(run(10)); //? var run = true; alert(run); //? function run(n){ return n x n; }
  • 4. Very^32 Important Function • Definition(Expression, Declaration) • Execution(invoke) • Creation (new) - not yet :(
  • 5. Associated with Function • this • execution context • scope(scope chain) • closure
  • 7. Define function • Function Expression • Function Declaration • Function Constructor
  • 8. Function Expression • Function Expression defines a function as a part of a large expression syntax • Functions defined via Functions Expressions can be named or anonymous • Function Expressions must not start with “function”
  • 9. ECMA 5(13.0) defines the syntax as function Identifieropt(FormalParametersListopt) { FunctionBody }
  • 10. Function Expression anonymous function var foo = function(x, y) { return x + y; } sum(20, 30); //return 50
  • 11. Function Expression named function var foo = function sum(x, y) { return x + y; } sum(20, 30); //return 50
  • 12. Function Expression self invoking function (function sum(x, y) { return x + y; })(20,30); sum(20, 30); //return 50
  • 13. Function Declaration • Function Declaration defines a named function variable without requiring variable assignment • Function Declarations occur as standalone constructs and cannot be nested within non- function blocks • Just as Variable Declarations must start with “var”, Function Declarations must begin with “function”
  • 14. ECMA 5(13.0) defines the syntax as function Identifier(FormalParametersListopt) { FunctionBody }
  • 15. Function Declaration named function function sum(x, y) { return x + y; } sum(20, 30); //return 50
  • 16. Function Constructor • When Function is called as part of a new expression, it is a constructor • It initialize the newly created object
  • 17. ECMA 5(15.3) defines the syntax as Function(p1, p2, ... ,pn, body);
  • 18. Function Constructor var foo = new Function(“x”, “y”, ”return x + y;”); foo(20, 30); //return 50
  • 19. What’s happen? Global activation object function outerFunc; assign arguments outerFunc context outerFunc Activation Object arguments Object variable instantiation arguments local variable definition local innerFunc innerFunc function instantiation [scope] function instantiation nested function definition assign [scope] assign this keyword
  • 20. Function Execution function outerFunc() { Global var local = 3; function outerFunc; function innerFunc() { [scope] return local++; Activation Object for function outerFunc }; local = 3, function innerFunc return innerFunc(); } [scope] alert(outerFunc()); //”4” Activation Object for function innerFunc
  • 21. Function Execution global context function outerFunc() { outerFunc var local = 3; outerFunc context function innerFunc() { outerFunc Activation Object local return local++; innerFunc }; [scope] return innerFunc(); innerFunc Object } innerFunc context alert(outerFunc()); //”4” innerFunc Activation Object [scope]
  • 22. Function Execution global context function outerFunc() { outerFunc var local = 3; outerFunc context function innerFunc() { outerFunc Activation Object local return local++; innerFunc }; [scope] return innerFunc(); innerFunc Object } innerFunc context alert(outerFunc()); //”4” innerFunc Activation Object [scope]
  • 23. Function Execution global context function outerFunc() { outerFunc var local = 3; outerFunc context function innerFunc() { outerFunc Activation Object local return local++; innerFunc }; [scope] return innerFunc(); innerFunc Object } innerFunc context alert(outerFunc()); //”4” innerFunc Activation Object [scope]
  • 24. Function Execution global context function outerFunc() { outerFunc var local = 3; outerFunc context function innerFunc() { outerFunc Activation Object local return local++; innerFunc }; [scope] return innerFunc(); innerFunc Object } innerFunc context alert(outerFunc()); //”4” innerFunc Activation Object [scope]
  • 25. Function Execution global context function outerFunc() { outerFunc var local = 3; outerFunc context function innerFunc() { outerFunc Activation Object local return local++; innerFunc }; [scope] return innerFunc(); innerFunc Object } innerFunc context alert(outerFunc()); //”4” innerFunc Activation Object [scope]
  • 26. Function Execution global context function outerFunc() { outerFunc var local = 3; outerFunc context function innerFunc() { outerFunc Activation Object local return local++; innerFunc }; [scope] = this return innerFunc(); innerFunc Object } innerFunc context alert(outerFunc()); //”4” innerFunc Activation Object [scope]
  • 27. Function Execution global context function outerFunc() { outerFunc var local = 3; outerFunc context function innerFunc() { outerFunc Activation Object local return local++; innerFunc }; [scope] = this return innerFunc(); innerFunc Object } innerFunc context alert(outerFunc()); //”4” innerFunc Activation Object [scope]
  • 28. Function Execution global context function outerFunc() { outerFunc var local = 3; outerFunc context function innerFunc() { outerFunc Activation Object local return local++; innerFunc }; [scope] = this return innerFunc(); innerFunc Object } innerFunc context alert(outerFunc()); //”4” innerFunc Activation Object [scope]
  • 29. Function Execution global context function outerFunc() { outerFunc var local = 3; outerFunc context function innerFunc() { outerFunc Activation Object local return local++; innerFunc }; [scope] = this return innerFunc(); innerFunc Object } innerFunc context alert(outerFunc()); //”4” innerFunc Activation Object [scope] = outerFunc
  • 30. Function Execution global context function outerFunc() { outerFunc var local = 3; outerFunc context function innerFunc() { outerFunc Activation Object local return local++; innerFunc }; [scope] = this return innerFunc(); innerFunc Object } innerFunc context alert(outerFunc()); //”4” innerFunc Activation Object [scope] = outerFunc
  • 31. Function Execution Summary I • • (Activation Object) • arguments length, callee . • arguments arguments • (Scope) • . • + ‘[scope]’ . • , • ‘this’ .
  • 32. Function Execution Summary II • • . • . • .( .) • • .
  • 33. Function Instantiation • • . • . • ‘[scope]’ .
  • 34. Top level Function var x = 3, y = 4; Global function outerFunc(i) { x = 3; y = 4; function outerFn; var x = true; y = y + i; alert(x); Activation Object for } function outerFn i = 5; x = true; alert(outerFunc(5)); Scope chain at execution of outerFn(5)
  • 35. Scope Chain diagram [scope] Global [scope] ... [scope] [scope]
  • 36. Variable Resolution var local = 3; function f4() { function f3() { local is here function f2() { function f1() { f1.[scope] Global return local; } return f1(); f2.[scope] ... } return f2(); } return f3(); f3.[scope] f4.[scope] } alert(f4());
  • 37. Scope Chain Point • (Function Object) ‘[scope]‘ . • ‘[scope]’ . • , ‘[scope]’ ‘ ’ . • . • ‘[scope]’ .