SlideShare a Scribd company logo
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

PDF
Scala - en bedre og mere effektiv Java?
PPTX
ODP
Meetup slides
PDF
Developing Applications with MySQL and Java for beginners
PDF
Scala - en bedre Java?
PDF
concurrency with GPars
PDF
Functional es6
ODP
GPars (Groovy Parallel Systems)
Scala - en bedre og mere effektiv Java?
Meetup slides
Developing Applications with MySQL and Java for beginners
Scala - en bedre Java?
concurrency with GPars
Functional es6
GPars (Groovy Parallel Systems)

What's hot (19)

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

Viewers also liked (6)

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

Similar to JS OO and Closures (20)

PDF
Say It With Javascript
KEY
JavaScript Classes and Inheritance
PDF
Object Oriented Programming in JavaScript
PPTX
Ch8(oop)
PDF
Impress Your Friends with EcmaScript 2015
PPTX
Front end fundamentals session 1: javascript core
PPTX
Object-Oriented Programming with PHP (part 1)
PPT
25-functions.ppt
PPTX
The ES Library for JavaScript Developers
PDF
Short intro to ECMAScript
PPTX
Awesomeness of JavaScript…almost
PDF
Core concepts-javascript
PPTX
FFW Gabrovo PMG - PHP OOP Part 3
KEY
Javascript tid-bits
PDF
Swift, functional programming, and the future of Objective-C
DOC
Jsphp 110312161301-phpapp02
PDF
Powerful JavaScript Tips and Best Practices
PDF
JS Level Up: Prototypes
PPT
Groovy unleashed
Say It With Javascript
JavaScript Classes and Inheritance
Object Oriented Programming in JavaScript
Ch8(oop)
Impress Your Friends with EcmaScript 2015
Front end fundamentals session 1: javascript core
Object-Oriented Programming with PHP (part 1)
25-functions.ppt
The ES Library for JavaScript Developers
Short intro to ECMAScript
Awesomeness of JavaScript…almost
Core concepts-javascript
FFW Gabrovo PMG - PHP OOP Part 3
Javascript tid-bits
Swift, functional programming, and the future of Objective-C
Jsphp 110312161301-phpapp02
Powerful JavaScript Tips and Best Practices
JS Level Up: Prototypes
Groovy unleashed

More from Jussi Pohjolainen (20)

PDF
Moved to Speakerdeck
PDF
Java Web Services
PDF
Box2D and libGDX
PDF
libGDX: Screens, Fonts and Preferences
PDF
libGDX: Tiled Maps
PDF
libGDX: User Input and Frame by Frame Animation
PDF
Intro to Building Android Games using libGDX
PDF
Advanced JavaScript Development
PDF
Introduction to JavaScript
PDF
Introduction to AngularJS
PDF
libGDX: Scene2D
PDF
libGDX: Simple Frame Animation
PDF
libGDX: Simple Frame Animation
PDF
libGDX: User Input
PDF
Implementing a Simple Game using libGDX
PDF
Building Android games using LibGDX
PDF
Android Threading
PDF
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
PDF
Creating Games for Asha - platform
PDF
Intro to Asha UI
Moved to Speakerdeck
Java Web Services
Box2D and libGDX
libGDX: Screens, Fonts and Preferences
libGDX: Tiled Maps
libGDX: User Input and Frame by Frame Animation
Intro to Building Android Games using libGDX
Advanced JavaScript Development
Introduction to JavaScript
Introduction to AngularJS
libGDX: Scene2D
libGDX: Simple Frame Animation
libGDX: Simple Frame Animation
libGDX: User Input
Implementing a Simple Game using libGDX
Building Android games using LibGDX
Android Threading
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Games for Asha - platform
Intro to Asha UI

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Machine Learning_overview_presentation.pptx
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Mushroom cultivation and it's methods.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Approach and Philosophy of On baking technology
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Getting Started with Data Integration: FME Form 101
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Encapsulation theory and applications.pdf
PPTX
1. Introduction to Computer Programming.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
NewMind AI Weekly Chronicles - August'25-Week II
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Machine Learning_overview_presentation.pptx
Univ-Connecticut-ChatGPT-Presentaion.pdf
OMC Textile Division Presentation 2021.pptx
Mushroom cultivation and it's methods.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Unlocking AI with Model Context Protocol (MCP)
Approach and Philosophy of On baking technology
A comparative study of natural language inference in Swahili using monolingua...
Reach Out and Touch Someone: Haptics and Empathic Computing
Spectral efficient network and resource selection model in 5G networks
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Assigned Numbers - 2025 - Bluetooth® Document
Getting Started with Data Integration: FME Form 101
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Building Integrated photovoltaic BIPV_UPV.pdf
Encapsulation theory and applications.pdf
1. Introduction to Computer Programming.pptx
Advanced methodologies resolving dimensionality complications for autism neur...

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();