SlideShare a Scribd company logo
1 of 74
Object Oriented JavaScript
VIVEK.P.S
http://vivekcek.wordpress.com
Agenda
• Objects in JavaScript
• Functions: Declaration, Expression and
Invocation
• this keyword
• Scopes and Closures
• Object oriented programming
Objects in JavaScript
Objects in JavaScript
• From one side, an object is an associative
array (called hash in some languages).
• It stores key-value pairs
Creating objects
• An empty object (you may also read as empty
associative array) is created with one of two
syntaxes:
• 1. o = new Object()
• 2. o = { } // the same
Literal syntax
It is also possible to create nested
objects
Non-existing properties, undefined
• But if the property does not exist,
then undefined is returned
Checking if a key exists
Iterating over keys-values
Object variables are references
• A variable which is assigned to object actually
keeps reference to it. That is, a variable stores
kind-of pointer to real data.
• The variable is a reference, not a value
An Example
Properties and methods
• You can store anything in object. Not just
simple values, but also functions.
Calling methods
• Note the this keyword
inside askName and sayHi. When a function is
called from the object, this becomes a
reference to this object.
The constructor function, “new”
• An object can be created, using
obj = { ..} syntax.
• Another way of creating an object in
JavaScript is to construct it by calling a
function with new directive.
A simple example
A simple example
• A function takes the following steps:
• Create this = {}.
• The function then runs and may change this,
add properties, methods etc.
• The resulting this is returned.
• So, the function constructs an object by
modifying this.
An example with the method
Summary
• Objects are associative arrays with additional features.
– Assign keys with obj[key] = value or obj.name = value
– Remove keys with delete obj.name
– Iterate over keys with for(key in obj), remember iteration order for
string keys is always in definition order, for numeric keys it may
change.
• Properties, which are functions, can be called as obj.method(). They
can refer to the object as this.
• Properties can be assigned and removed any time.
• A function can create new objects when run in constructor mode
as new Func(params).It takes this, which is initially an empty object,
and assigns properties to it. The result is returned (unless the
function has explicit return anotherObject call).
Functions: declarations, expressions
and Invocation
The syntax
• function f(arg1, arg2, ...) {
... code ...
}
Returning a value
• use return statement
If a function does not return anything, it’s result is
considered to be a special value, undefined
• function getNothing() {
// no return
}
Local variables
• variables, defined by var. Such variables are
called local and are only visible inside the
function
Function Declaration
• Function Declarations are parsed at pre-
execution stage, when the browser prepares
to execute the code.
• why the function declared this way can be
called both after and before the definition
Function Expression
Function Expression
• Function Expressions are created when the
execution flow reaches them. As a
consequence, Function Expressions can be
used only after they are executed.
Function is a value
• A function in JavaScript is a regular value. We
could even output it
• a function can be assigned, passed as a
parameter for another function and so on.
Running at place
• Running in place is mostly used when we want
to do the job involving local variables. We
don’t want our local variables to become
global, so wrap the code into a function.
• After the execution, the global namespace is
still clean. That’s a good practice.
Named function expressions
• The syntax is called named function expression
• the name is visible inside the function only
• NFEs exist to allow recursive calls from
anonymous functions
Summary
• Functions in JavaScript are regular values.
They can be assigned, passed around and
called when needed.
• A function which returns nothing actually
returns special value: undefined.
• Use verbs to name functions. Short names are
allowable in two edge cases: a name is used in
the nearest code only, or it is extremely widely
used.
Summary
this
Introduction
• The value of this is dynamic in JavaScript
• It is determined when function is called, not
when it is declared
• Any function may use this. It doesn’t matter if
the function is assigned to the object or not
• The real value of this is evaluated in the call
time anyway, and there are 4 possible cases
First, when called as a method
• If a function is called from the object (either
dot or square bracket will do), this refers to
this object.
• In the example above, func is initially apart
from the object. But when
called john.sayHi() sets this to the object
before dot: john.
Second, when called as a function
• If a function uses this, then it is meant to be
called as a method. A simple func() call is
usually a bug
Third, in new
• When a new function is called, this is
initialized as a new object
Fourth, explicit this
• A function can be called with
explicit this value. This is done out by one of
two methods: call or apply
Call
apply
• The func.apply is same as func.call, but it
accepts an array of arguments instead of a list
• The following two lines are same:
• func.call(john, 'firstName', 'surname')
Summary
Scopes and Closures
Initialization of functions and variables
• In JavaScript, all local variables and functions
are properties of the special internal object,
called LexicalEnvironment
• The top-level LexicalEnvironment in browser
is window. It is also called a global object.
Instantiation of top-level variables
• When the script is going to be executed, there
is a pre-processing stage called variables
instantiation.
• The top-level LexicalEnvironment in browser
is window. It is also called a global object.
• the browser finds function f, creates the
function and stores it as window.f
• Function Declarations are initialized before
the code is executed.
• As a side effect, f can be called before it is
declared (Hoisting)
• Second, the interpreter scans
for var declarations and
creates window properties. Assignments are
not executed at this stage. All variables start
as undefined.
• FunctionDeclarations become ready-to-use
functions. That allows to call a function before
it’s declaration.
• Variables start as undefined.
• All assignments happen later, when the
execution reaches them
Function variables
• When the interpreter is preparing to start
function code execution, before the first line is
run, an empty LexicalEnvironment is created
and populated with arguments, local variables
and nested functions.
• Then the function code runs, eventually
assignments are executed.A variable
assignment internally means that the
corresponding property of
theLexicalEnvironment gets a new value.
Closures
• So variable is a property of
the LexicalEnvironment object
• Here we discuss access to outer variables and
nested functions
Access to outer variables
Nested functions
• Functions can be nested one inside another,
forming a chain of LexicalEnvironments which
can also be called a scope chain
Closures
• Nested function may continue to live after the
outer function has finished:
Closure
• The inner function keeps a reference to the
outer LexicalEnvironment.
• The inner function may access variables from it
any time even if the outer function is finished.
• The browser keeps the LexicalEnvironment and
all it’s properties(variables) in memory until there
is an inner function which references it.
• This is called a closure.
[[Scope]] for new Function
• There is an exception to general scope binding
rule. When you create a function using new
Function, it’s[[Scope]] points to window, not
to current LexicalEnvironment.
Summary
• How variables are handled in JavaScript.
• How scopes work.
• What is a closure and how to use it.
• Possible pitfalls and subtles in working with
closures.
• In JavaScript, a variable can be declared after it
has been used (Hoisting).
• In other words; a variable can be used before it
has been declared (Hoisting).
Object Oriented Programming
Prototypal inheritance
• In JavaScript, the inheritance is prototype-
based. That means that there are no classes.
Instead, an object inherits from another
object
Object.create, Object.getPrototypeOf
• The __proto__ is a non-standard property,
provided by Firefox/Chrome. In other
browsers the property still exists internally,
but it is hidden
The prototype
• There is a good and crossbrowser way of
setting __proto__. It requires the use of
constructor functions.
hasOwnProperty
• All objects have hasOwnProperty method
which allows to check if a property belongs to
the object or its prototype.
Summary
• The inheritance is implemented through a
special property __proto__ (named
[[Prototype]] in the specification).
• When a property is accessed, and the
interpreter can’t find it in the object, it follows
the __proto__link and searches it there.
• The value of this for function properties is set
to the object, not its prototype.
• Assignment obj.prop = val and deletion delete
obj.prop
OOP patterns
Module pattern
Revealing Module pattern
var self = this
var self = this

More Related Content

What's hot

Java Script Language Tutorial
Java Script Language TutorialJava Script Language Tutorial
Java Script Language Tutorial
vikram singh
 

What's hot (20)

JavaScript Beyond jQuery
JavaScript Beyond jQueryJavaScript Beyond jQuery
JavaScript Beyond jQuery
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Virtual Function
Virtual FunctionVirtual Function
Virtual Function
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Books
BooksBooks
Books
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Ajaxworld
AjaxworldAjaxworld
Ajaxworld
 
Javascript
JavascriptJavascript
Javascript
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Introduction to functional programming with java 8
Introduction to functional programming with java 8Introduction to functional programming with java 8
Introduction to functional programming with java 8
 
Java Script Language Tutorial
Java Script Language TutorialJava Script Language Tutorial
Java Script Language Tutorial
 
Lambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzLambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian Goetz
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
 
JS - Basics
JS - BasicsJS - Basics
JS - Basics
 

Viewers also liked (6)

Stem student center concept final
Stem student center concept finalStem student center concept final
Stem student center concept final
 
Student Center Overview
Student Center Overview Student Center Overview
Student Center Overview
 
Romania london sept 2012 - part2
Romania london sept 2012 - part2Romania london sept 2012 - part2
Romania london sept 2012 - part2
 
The Manhattanville Student Center Pavilion
The Manhattanville Student Center PavilionThe Manhattanville Student Center Pavilion
The Manhattanville Student Center Pavilion
 
B.Arch Course Portfolio
B.Arch Course PortfolioB.Arch Course Portfolio
B.Arch Course Portfolio
 
Concept study of mahindra united world college,pune and pearl academy of fash...
Concept study of mahindra united world college,pune and pearl academy of fash...Concept study of mahindra united world college,pune and pearl academy of fash...
Concept study of mahindra united world college,pune and pearl academy of fash...
 

Similar to Object oriented java script

JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
Chamnap Chhorn
 

Similar to Object oriented java script (20)

Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptx
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Functions
FunctionsFunctions
Functions
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
 
UNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year csUNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year cs
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
 
JavsScript OOP
JavsScript OOPJavsScript OOP
JavsScript OOP
 
Javascript Workshop
Javascript WorkshopJavascript Workshop
Javascript Workshop
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classes
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closures
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
 
About Python
About PythonAbout Python
About Python
 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept it
 
Javascript talk
Javascript talkJavascript talk
Javascript talk
 
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++
 
Advance JS and oop
Advance JS and oopAdvance JS and oop
Advance JS and oop
 
PHP- Introduction to Object Oriented PHP
PHP-  Introduction to Object Oriented PHPPHP-  Introduction to Object Oriented PHP
PHP- Introduction to Object Oriented PHP
 

More from vivek p s (6)

Conversational UI Bot Framework
Conversational UI Bot FrameworkConversational UI Bot Framework
Conversational UI Bot Framework
 
Microsoft Bot Framework
Microsoft Bot FrameworkMicrosoft Bot Framework
Microsoft Bot Framework
 
Azure functions
Azure functionsAzure functions
Azure functions
 
Cloud computing Azure
Cloud computing AzureCloud computing Azure
Cloud computing Azure
 
Surya namskar
Surya namskarSurya namskar
Surya namskar
 
Object Oriented Principle’s
Object Oriented Principle’sObject Oriented Principle’s
Object Oriented Principle’s
 

Recently uploaded

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 

Object oriented java script

  • 2. Agenda • Objects in JavaScript • Functions: Declaration, Expression and Invocation • this keyword • Scopes and Closures • Object oriented programming
  • 4. Objects in JavaScript • From one side, an object is an associative array (called hash in some languages). • It stores key-value pairs
  • 5. Creating objects • An empty object (you may also read as empty associative array) is created with one of two syntaxes: • 1. o = new Object() • 2. o = { } // the same
  • 6.
  • 8. It is also possible to create nested objects
  • 9. Non-existing properties, undefined • But if the property does not exist, then undefined is returned
  • 10. Checking if a key exists
  • 12. Object variables are references • A variable which is assigned to object actually keeps reference to it. That is, a variable stores kind-of pointer to real data. • The variable is a reference, not a value
  • 14. Properties and methods • You can store anything in object. Not just simple values, but also functions.
  • 15. Calling methods • Note the this keyword inside askName and sayHi. When a function is called from the object, this becomes a reference to this object.
  • 16. The constructor function, “new” • An object can be created, using obj = { ..} syntax. • Another way of creating an object in JavaScript is to construct it by calling a function with new directive.
  • 18. A simple example • A function takes the following steps: • Create this = {}. • The function then runs and may change this, add properties, methods etc. • The resulting this is returned. • So, the function constructs an object by modifying this.
  • 19. An example with the method
  • 20. Summary • Objects are associative arrays with additional features. – Assign keys with obj[key] = value or obj.name = value – Remove keys with delete obj.name – Iterate over keys with for(key in obj), remember iteration order for string keys is always in definition order, for numeric keys it may change. • Properties, which are functions, can be called as obj.method(). They can refer to the object as this. • Properties can be assigned and removed any time. • A function can create new objects when run in constructor mode as new Func(params).It takes this, which is initially an empty object, and assigns properties to it. The result is returned (unless the function has explicit return anotherObject call).
  • 22. The syntax • function f(arg1, arg2, ...) { ... code ... }
  • 23. Returning a value • use return statement If a function does not return anything, it’s result is considered to be a special value, undefined • function getNothing() { // no return }
  • 24. Local variables • variables, defined by var. Such variables are called local and are only visible inside the function
  • 25. Function Declaration • Function Declarations are parsed at pre- execution stage, when the browser prepares to execute the code. • why the function declared this way can be called both after and before the definition
  • 27. Function Expression • Function Expressions are created when the execution flow reaches them. As a consequence, Function Expressions can be used only after they are executed.
  • 28. Function is a value • A function in JavaScript is a regular value. We could even output it • a function can be assigned, passed as a parameter for another function and so on.
  • 29. Running at place • Running in place is mostly used when we want to do the job involving local variables. We don’t want our local variables to become global, so wrap the code into a function. • After the execution, the global namespace is still clean. That’s a good practice.
  • 30. Named function expressions • The syntax is called named function expression • the name is visible inside the function only • NFEs exist to allow recursive calls from anonymous functions
  • 31. Summary • Functions in JavaScript are regular values. They can be assigned, passed around and called when needed. • A function which returns nothing actually returns special value: undefined. • Use verbs to name functions. Short names are allowable in two edge cases: a name is used in the nearest code only, or it is extremely widely used.
  • 33. this
  • 34. Introduction • The value of this is dynamic in JavaScript • It is determined when function is called, not when it is declared • Any function may use this. It doesn’t matter if the function is assigned to the object or not • The real value of this is evaluated in the call time anyway, and there are 4 possible cases
  • 35. First, when called as a method • If a function is called from the object (either dot or square bracket will do), this refers to this object. • In the example above, func is initially apart from the object. But when called john.sayHi() sets this to the object before dot: john.
  • 36. Second, when called as a function • If a function uses this, then it is meant to be called as a method. A simple func() call is usually a bug
  • 37. Third, in new • When a new function is called, this is initialized as a new object
  • 38. Fourth, explicit this • A function can be called with explicit this value. This is done out by one of two methods: call or apply
  • 39. Call
  • 40. apply • The func.apply is same as func.call, but it accepts an array of arguments instead of a list • The following two lines are same: • func.call(john, 'firstName', 'surname')
  • 43. Initialization of functions and variables • In JavaScript, all local variables and functions are properties of the special internal object, called LexicalEnvironment • The top-level LexicalEnvironment in browser is window. It is also called a global object.
  • 44. Instantiation of top-level variables • When the script is going to be executed, there is a pre-processing stage called variables instantiation. • The top-level LexicalEnvironment in browser is window. It is also called a global object.
  • 45. • the browser finds function f, creates the function and stores it as window.f • Function Declarations are initialized before the code is executed. • As a side effect, f can be called before it is declared (Hoisting)
  • 46. • Second, the interpreter scans for var declarations and creates window properties. Assignments are not executed at this stage. All variables start as undefined.
  • 47. • FunctionDeclarations become ready-to-use functions. That allows to call a function before it’s declaration. • Variables start as undefined. • All assignments happen later, when the execution reaches them
  • 48. Function variables • When the interpreter is preparing to start function code execution, before the first line is run, an empty LexicalEnvironment is created and populated with arguments, local variables and nested functions.
  • 49. • Then the function code runs, eventually assignments are executed.A variable assignment internally means that the corresponding property of theLexicalEnvironment gets a new value.
  • 50. Closures • So variable is a property of the LexicalEnvironment object • Here we discuss access to outer variables and nested functions
  • 51. Access to outer variables
  • 52. Nested functions • Functions can be nested one inside another, forming a chain of LexicalEnvironments which can also be called a scope chain
  • 53. Closures • Nested function may continue to live after the outer function has finished:
  • 54.
  • 55. Closure • The inner function keeps a reference to the outer LexicalEnvironment. • The inner function may access variables from it any time even if the outer function is finished. • The browser keeps the LexicalEnvironment and all it’s properties(variables) in memory until there is an inner function which references it. • This is called a closure.
  • 56. [[Scope]] for new Function • There is an exception to general scope binding rule. When you create a function using new Function, it’s[[Scope]] points to window, not to current LexicalEnvironment.
  • 57. Summary • How variables are handled in JavaScript. • How scopes work. • What is a closure and how to use it. • Possible pitfalls and subtles in working with closures. • In JavaScript, a variable can be declared after it has been used (Hoisting). • In other words; a variable can be used before it has been declared (Hoisting).
  • 59. Prototypal inheritance • In JavaScript, the inheritance is prototype- based. That means that there are no classes. Instead, an object inherits from another object
  • 60.
  • 61.
  • 62.
  • 63.
  • 64. Object.create, Object.getPrototypeOf • The __proto__ is a non-standard property, provided by Firefox/Chrome. In other browsers the property still exists internally, but it is hidden
  • 65.
  • 66. The prototype • There is a good and crossbrowser way of setting __proto__. It requires the use of constructor functions.
  • 67.
  • 68. hasOwnProperty • All objects have hasOwnProperty method which allows to check if a property belongs to the object or its prototype.
  • 69. Summary • The inheritance is implemented through a special property __proto__ (named [[Prototype]] in the specification). • When a property is accessed, and the interpreter can’t find it in the object, it follows the __proto__link and searches it there. • The value of this for function properties is set to the object, not its prototype. • Assignment obj.prop = val and deletion delete obj.prop
  • 73. var self = this
  • 74. var self = this