SlideShare a Scribd company logo
1 of 19
Download to read offline
JS	
  AND	
  OO	
  
About	
  Objects	
  
•  Everything	
  (except	
  basic	
  types)	
  are	
  objects	
  
– Including	
  func=ons	
  and	
  arrays	
  
•  Object	
  contains	
  proper=es	
  and	
  methods	
  
– Collec=on	
  of	
  name-­‐value	
  pairs	
  
– Names	
  are	
  strings,	
  values	
  can	
  be	
  anything	
  
– Proper=es	
  and	
  methods	
  can	
  be	
  added	
  at	
  run=me	
  
•  Objects	
  can	
  inherit	
  other	
  objects	
  
Object	
  Literal	
  
var mystring = “hello!”;
var myarray = [“element1”, “element2”];
var circle1 = {radius: 9, getArea : someFunction };
var circle2 = {
radius: 9,
getRadius: function() {
return this.radius;
}
}
No	
  Classes!	
  
•  One	
  of	
  the	
  simplest	
  way	
  to	
  create	
  object	
  
– var obj = new Object();
– obj.x = 10;
– obj.y = 12;
– obj.method = function() { … }
•  This	
  adds	
  dynamically	
  two	
  proper=es	
  to	
  the	
  
obj	
  –	
  object!	
  
•  Object	
  is	
  built	
  –	
  in	
  data	
  type	
  
“Class”	
  
•  To	
  define	
  a	
  class,	
  define	
  a	
  func=on	
  
function Foo() {
this.x = 1;
this.y = 1;
}
•  var obj = new Foo();
•  Internally	
  a	
  Object	
  is	
  created	
  
Example	
  
function Circle(radius)
{
this.radius = radius;
this.getArea = function()
{
return (this.radius * this.radius) * Math.PI;
};
}
var myobj = new Circle(5);
document.write(myobj.getArea());
About	
  Namespaces	
  
•  Avoid	
  pollu=ng	
  global	
  scope	
  
– Use	
  namespaces!	
  
– Helps	
  avoid	
  clashes	
  between	
  your	
  code	
  and	
  third-­‐
party	
  libraries	
  
•  Namespaces	
  don’t	
  have	
  dedicated	
  syntax	
  
built	
  into	
  the	
  language	
  
•  It’s	
  possible	
  to	
  get	
  same	
  benefits	
  by	
  crea=ng	
  
single	
  global	
  object	
  and	
  add	
  all	
  other	
  objects	
  
and	
  func=ons	
  to	
  this	
  object	
  
Example	
  about	
  Namespaces	
  
"use strict";
// If first operand is truthy, then the result is
// first operand, else the result is second operand
// By convention namespaces are written in capitals
var MYSPACE = MYSPACE || {};
MYSPACE.Dog = function (name) {
this.name = name;
this.getName = function () {
return name;
};
};
var spot = new MYSPACE.Dog("Spot");
print(spot.getName());
Arrays	
  
•  Arrays	
  in	
  JS	
  are	
  dynamic,	
  content	
  can	
  be	
  
added	
  and	
  removed	
  
•  Arrays	
  are	
  also	
  objects	
  (Array	
  “class”	
  inherit	
  
Object)	
  
– concat(),	
  join(),	
  pop(),	
  push(),	
  slice(),	
  sort(),	
  splice()	
  
Example	
  
"use strict";
var array1 = []; // or new Array()
var array2 = ['a', 'b', 'c'];
print(array2.length);
delete array2[1];
for(var i = 0; i<array2.length; i++) {
print(array2[i]);
}
Func=ons	
  
•  Every	
  func=on	
  in	
  JS	
  is	
  Func=on	
  object	
  
–  Can	
  be	
  passed	
  as	
  arguments	
  
–  Can	
  store	
  name	
  /	
  value	
  pairs	
  
–  Can	
  be	
  anonymous	
  or	
  named	
  
•  Usage	
  (Don’t	
  use	
  this,	
  it’s	
  not	
  efficient)	
  
–  var myfunction = new Function("a","b",
"return a+b;");
–  print(myfunction(3,3));
•  Only	
  func=ons	
  have	
  scope,	
  regular	
  {blocks)	
  don’t	
  
•  Inner	
  func=on	
  can	
  have	
  access	
  to	
  outer	
  func=on’s	
  
proper=es	
  and	
  parameters	
  
Func=on	
  Arguments	
  
•  The	
  arguments	
  object	
  is	
  a	
  local	
  object	
  
available	
  within	
  all	
  func=ons	
  
•  Each	
  func=on	
  has	
  access	
  to	
  special	
  parameter	
  
called	
  arguments	
  
– Contains	
  the	
  funcAon	
  arguments	
  
•  It’s	
  an	
  array	
  like	
  object	
  (but	
  not	
  an	
  array)	
  
– Only	
  arguments.length	
  available	
  
Example	
  
"use strict";
function myConcat(separator) {
var result = "";
// iterate through non-separator arguments
for (var i = 1; i < arguments.length; i++) {
result += arguments[i] + separator;
}
return result;
}
// returns "red, orange, blue, "
print(myConcat(", ", "red", "orange", "blue"));
// returns "elephant; giraffe; lion; cheetah; "
print(myConcat("; ", "elephant", "giraffe", "lion", "cheetah"));
// returns "sage. basil. oregano. pepper. parsley. "
print(myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"));
Func=onal	
  Scoping	
  
"use strict";
function init() {
// local variable name
var name = "Hello World";
// inner function
function displayName() {
// uses outer functions variable
print(name);
}
displayName();
}
init();
Returning	
  a	
  Inner	
  Func=on	
  
"use strict";
function makeFunc() {
var name = "Hello World";
function displayName() {
print(name);
}
// When returning a inner function, it’s a closure!
// Local variables are added to the closure as a reference
return displayName;
}
// Is “Hello World” printed?
var myFunc = makeFunc();
myFunc();
About	
  Closures	
  
•  myFunc	
  is	
  a	
  closure	
  
•  Special	
  kind	
  of	
  object	
  that	
  combines	
  
– A	
  func=on	
  
– Environment	
  in	
  which	
  func=on	
  was	
  created	
  
•  Environment	
  consists	
  of	
  any	
  local	
  variables	
  that	
  were	
  
in-­‐scope	
  at	
  the	
  =me	
  closure	
  was	
  created	
  
•  myFunc	
  is	
  a	
  closure	
  that	
  has	
  displayName	
  and	
  name	
  
Private	
  methods	
  with	
  Closures	
  
"use strict";
function getPerson(name) {
var privateMember = "hello world!", obj;
obj = {
shout: function () {
print(name + " shouts " + privateMember);
},
say: function () {
print(name + " say " + privateMember);
}
};
return obj;
};
var person = getPerson("Jack");
// Does not work!
print(person.privateMember);
person.shout();
person.say();
Private	
  methods	
  with	
  Closures	
  
"use strict";
var person = (function(name) {
var privateMember = "hello world!", obj;
obj = {
setName: function(myName) {
name = myName;
},
shout: function () {
print(name + " shouts " + privateMember);
},
say: function () {
print(name + " say " + privateMember);
}
};
return obj;
})("");
person.setName("Jack");
person.shout();
person.say();
this	
  
function foo() {
// adds prop to global object
this.prop = 12;
}
var obj = {
method: function() {
// goes to obj
this.prop = 12;
}
};
obj.method();
function Dog(name) {
// Refers to object being created!
this.name = name;
this.sayHello = function() {
print(this.name + " says hello!");
};
}
var dog = new Dog("Spot");
dog.sayHello();

More Related Content

What's hot

An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scalaXing
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arraysHassan Dar
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うbpstudy
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
dotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsdotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsRob Napier
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers輝 子安
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)Makoto Yamazaki
 
There's a Prolog in your Scala!
There's a Prolog in your Scala!There's a Prolog in your Scala!
There's a Prolog in your Scala!George Leontiev
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kirill Rozov
 
concurrency gpars
concurrency gparsconcurrency gpars
concurrency gparsPaul King
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Introthnetos
 

What's hot (19)

Java script arrays
Java script arraysJava script arrays
Java script arrays
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
dotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsdotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World Protocols
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 
Grammarware Memes
Grammarware MemesGrammarware Memes
Grammarware Memes
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
 
There's a Prolog in your Scala!
There's a Prolog in your Scala!There's a Prolog in your Scala!
There's a Prolog in your Scala!
 
Meet scala
Meet scalaMeet scala
Meet scala
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
concurrency gpars
concurrency gparsconcurrency gpars
concurrency gpars
 
Python - Lecture 4
Python - Lecture 4Python - Lecture 4
Python - Lecture 4
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
 

Viewers also liked

Www.edupristine.com blog-6-steps-to-score-70-in-fra--.uk4 jlkkdexo.pdfmyurl
Www.edupristine.com blog-6-steps-to-score-70-in-fra--.uk4 jlkkdexo.pdfmyurlWww.edupristine.com blog-6-steps-to-score-70-in-fra--.uk4 jlkkdexo.pdfmyurl
Www.edupristine.com blog-6-steps-to-score-70-in-fra--.uk4 jlkkdexo.pdfmyurlPrasad Ajinkya
 
HTML5 e Css3 - 8 | WebMaster & WebDesigner
HTML5 e Css3 - 8 | WebMaster & WebDesignerHTML5 e Css3 - 8 | WebMaster & WebDesigner
HTML5 e Css3 - 8 | WebMaster & WebDesignerMatteo Magni
 
DU Master Researcher Research Assessment And Scholarly Engagement Workshops 2...
DU Master Researcher Research Assessment And Scholarly Engagement Workshops 2...DU Master Researcher Research Assessment And Scholarly Engagement Workshops 2...
DU Master Researcher Research Assessment And Scholarly Engagement Workshops 2...Dillard University Library
 
How-To Deploy a Riak Cluster in 5 Minutes on GoGrid
How-To Deploy a Riak Cluster in 5 Minutes on GoGridHow-To Deploy a Riak Cluster in 5 Minutes on GoGrid
How-To Deploy a Riak Cluster in 5 Minutes on GoGridGoGrid Cloud Hosting
 

Viewers also liked (6)

Www.edupristine.com blog-6-steps-to-score-70-in-fra--.uk4 jlkkdexo.pdfmyurl
Www.edupristine.com blog-6-steps-to-score-70-in-fra--.uk4 jlkkdexo.pdfmyurlWww.edupristine.com blog-6-steps-to-score-70-in-fra--.uk4 jlkkdexo.pdfmyurl
Www.edupristine.com blog-6-steps-to-score-70-in-fra--.uk4 jlkkdexo.pdfmyurl
 
HTML5 e Css3 - 8 | WebMaster & WebDesigner
HTML5 e Css3 - 8 | WebMaster & WebDesignerHTML5 e Css3 - 8 | WebMaster & WebDesigner
HTML5 e Css3 - 8 | WebMaster & WebDesigner
 
DU Master Researcher Research Assessment And Scholarly Engagement Workshops 2...
DU Master Researcher Research Assessment And Scholarly Engagement Workshops 2...DU Master Researcher Research Assessment And Scholarly Engagement Workshops 2...
DU Master Researcher Research Assessment And Scholarly Engagement Workshops 2...
 
Intro to 4-AOT9 Course
Intro to 4-AOT9 CourseIntro to 4-AOT9 Course
Intro to 4-AOT9 Course
 
Presentation1
Presentation1Presentation1
Presentation1
 
How-To Deploy a Riak Cluster in 5 Minutes on GoGrid
How-To Deploy a Riak Cluster in 5 Minutes on GoGridHow-To Deploy a Riak Cluster in 5 Minutes on GoGrid
How-To Deploy a Riak Cluster in 5 Minutes on GoGrid
 

Similar to JS OO and Closures

JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritancemarcheiligers
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptzand3rs
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Lukas Ruebbelke
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreWeb Zhao
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Bozhidar Boshnakov
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3Toni Kolev
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CAlexis Gallagher
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: PrototypesVernon Kesner
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 

Similar to JS OO and Closures (20)

Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritance
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
 
Js
JsJs
Js
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 

More from Jussi Pohjolainen

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 

More from Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 

Recently uploaded

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
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
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 

Recently uploaded (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor 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
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

JS OO and Closures

  • 2. About  Objects   •  Everything  (except  basic  types)  are  objects   – Including  func=ons  and  arrays   •  Object  contains  proper=es  and  methods   – Collec=on  of  name-­‐value  pairs   – Names  are  strings,  values  can  be  anything   – Proper=es  and  methods  can  be  added  at  run=me   •  Objects  can  inherit  other  objects  
  • 3. Object  Literal   var mystring = “hello!”; var myarray = [“element1”, “element2”]; var circle1 = {radius: 9, getArea : someFunction }; var circle2 = { radius: 9, getRadius: function() { return this.radius; } }
  • 4. No  Classes!   •  One  of  the  simplest  way  to  create  object   – var obj = new Object(); – obj.x = 10; – obj.y = 12; – obj.method = function() { … } •  This  adds  dynamically  two  proper=es  to  the   obj  –  object!   •  Object  is  built  –  in  data  type  
  • 5. “Class”   •  To  define  a  class,  define  a  func=on   function Foo() { this.x = 1; this.y = 1; } •  var obj = new Foo(); •  Internally  a  Object  is  created  
  • 6. Example   function Circle(radius) { this.radius = radius; this.getArea = function() { return (this.radius * this.radius) * Math.PI; }; } var myobj = new Circle(5); document.write(myobj.getArea());
  • 7. About  Namespaces   •  Avoid  pollu=ng  global  scope   – Use  namespaces!   – Helps  avoid  clashes  between  your  code  and  third-­‐ party  libraries   •  Namespaces  don’t  have  dedicated  syntax   built  into  the  language   •  It’s  possible  to  get  same  benefits  by  crea=ng   single  global  object  and  add  all  other  objects   and  func=ons  to  this  object  
  • 8. Example  about  Namespaces   "use strict"; // If first operand is truthy, then the result is // first operand, else the result is second operand // By convention namespaces are written in capitals var MYSPACE = MYSPACE || {}; MYSPACE.Dog = function (name) { this.name = name; this.getName = function () { return name; }; }; var spot = new MYSPACE.Dog("Spot"); print(spot.getName());
  • 9. Arrays   •  Arrays  in  JS  are  dynamic,  content  can  be   added  and  removed   •  Arrays  are  also  objects  (Array  “class”  inherit   Object)   – concat(),  join(),  pop(),  push(),  slice(),  sort(),  splice()  
  • 10. Example   "use strict"; var array1 = []; // or new Array() var array2 = ['a', 'b', 'c']; print(array2.length); delete array2[1]; for(var i = 0; i<array2.length; i++) { print(array2[i]); }
  • 11. Func=ons   •  Every  func=on  in  JS  is  Func=on  object   –  Can  be  passed  as  arguments   –  Can  store  name  /  value  pairs   –  Can  be  anonymous  or  named   •  Usage  (Don’t  use  this,  it’s  not  efficient)   –  var myfunction = new Function("a","b", "return a+b;"); –  print(myfunction(3,3)); •  Only  func=ons  have  scope,  regular  {blocks)  don’t   •  Inner  func=on  can  have  access  to  outer  func=on’s   proper=es  and  parameters  
  • 12. Func=on  Arguments   •  The  arguments  object  is  a  local  object   available  within  all  func=ons   •  Each  func=on  has  access  to  special  parameter   called  arguments   – Contains  the  funcAon  arguments   •  It’s  an  array  like  object  (but  not  an  array)   – Only  arguments.length  available  
  • 13. Example   "use strict"; function myConcat(separator) { var result = ""; // iterate through non-separator arguments for (var i = 1; i < arguments.length; i++) { result += arguments[i] + separator; } return result; } // returns "red, orange, blue, " print(myConcat(", ", "red", "orange", "blue")); // returns "elephant; giraffe; lion; cheetah; " print(myConcat("; ", "elephant", "giraffe", "lion", "cheetah")); // returns "sage. basil. oregano. pepper. parsley. " print(myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"));
  • 14. Func=onal  Scoping   "use strict"; function init() { // local variable name var name = "Hello World"; // inner function function displayName() { // uses outer functions variable print(name); } displayName(); } init();
  • 15. Returning  a  Inner  Func=on   "use strict"; function makeFunc() { var name = "Hello World"; function displayName() { print(name); } // When returning a inner function, it’s a closure! // Local variables are added to the closure as a reference return displayName; } // Is “Hello World” printed? var myFunc = makeFunc(); myFunc();
  • 16. About  Closures   •  myFunc  is  a  closure   •  Special  kind  of  object  that  combines   – A  func=on   – Environment  in  which  func=on  was  created   •  Environment  consists  of  any  local  variables  that  were   in-­‐scope  at  the  =me  closure  was  created   •  myFunc  is  a  closure  that  has  displayName  and  name  
  • 17. Private  methods  with  Closures   "use strict"; function getPerson(name) { var privateMember = "hello world!", obj; obj = { shout: function () { print(name + " shouts " + privateMember); }, say: function () { print(name + " say " + privateMember); } }; return obj; }; var person = getPerson("Jack"); // Does not work! print(person.privateMember); person.shout(); person.say();
  • 18. Private  methods  with  Closures   "use strict"; var person = (function(name) { var privateMember = "hello world!", obj; obj = { setName: function(myName) { name = myName; }, shout: function () { print(name + " shouts " + privateMember); }, say: function () { print(name + " say " + privateMember); } }; return obj; })(""); person.setName("Jack"); person.shout(); person.say();
  • 19. this   function foo() { // adds prop to global object this.prop = 12; } var obj = { method: function() { // goes to obj this.prop = 12; } }; obj.method(); function Dog(name) { // Refers to object being created! this.name = name; this.sayHello = function() { print(this.name + " says hello!"); }; } var dog = new Dog("Spot"); dog.sayHello();