SlideShare una empresa de Scribd logo
1 de 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]’
                                                             .

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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 a 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 a 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
 

Más de 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
 

Más de 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
 

Último

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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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
 
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
 
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
 
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
 
🐬 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
 

Último (20)

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
 
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
 
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...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
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
 
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
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 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
 
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
 
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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

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]’ .