SlideShare a Scribd company logo
Getting from Scripts to Applications Donald J. Sipe  |  Refresh Jacksonville  |  November 11 th  2008
JavaScript We are here Pseudoclassical Inheritance Hello World!
JavaScript What we’ll be talking about OOP Basics Scope Closures Context Appling to OOP Constructors Methods Public Private Privileged
But First... Some handy tools Here are some handy things you might not know JavaScript can do: Object-literal notation Anonymous functions Binary assignment Dot-style  and  array-style access of properties
Handy Tools Object Literal Notation— Makes JSON possible // The old way var  myObject = new Object(); myObject.val = “test”; // Using object literal notation var  myObject = {   val: “test” };
Handy Tools Object Literal Notation // The old way var  myArray = new Array(1, 30, “Refresh”); // Using object literal notation var  myArray = [1, 30, “Refresh”];
Handy Tools Anonymous Functions In JavaScript, functions are treated as values, which means: Functions can be assigned to variables Functions can be passed as arguments to other functions
Handy Tools Anonymous Functions // Using an anonymous function as an argument setTimeout(  function  () {   alert( “Refresh” );   }, 1000 ); // Using a function as a variable var  myFunc =  function  () {    alert( “Refresh” );  }; setTimeout(myFunc, 1000);
Handy Tools Anonymous Functions : Building a “scope bubble” Using an anonymous function to wrap code you don’t want in the global scope var  globalVar = “Refresh”;  // Global scope // Create a scope bubble (  function  () {   var  privateVar = “Jacksonville”;   alert( globalVar + “ ” + privateVar ); } )(); alert (privateVar ==  undefined );
Handy Tools Binary Assignment Set a default value only if the variable doesn’t have a value yet // Traditional ternary assignment var  myVar = myVar  ?  myVar  :  0; // Binary assignment var  myVar = myVal || 0;
Handy Tools Dot-Style and Array-Style property access var  sampleObj = {   color: “blue”,   width: “16px” }; // Traditional dot-style access alert( sampleObj.color == “blue” ); // Alternative array-style access alert( sampleObj[“width”] == “16px” );
Scope, Closures, and Context
Scope Only functions have scope.  Blocks ( if ,  while ,  for ,  switch ) do not. All variables are within the global scope unless they are defined within a  function . All global variables actually become properties of the  window   object When variables are  not  declared using the  var   keyword, they decared globally.
Scope var  foo = “orig”;  //  foo  is now a global variable if  ( true ) {   foo = “new”;  // Global  foo  now equals “new” } // create function to modify its own  foo  variable function  test () {   var  foo = “old”; } test(); alert( foo == “new” );  // Global  foo  still equals “new”
Scope If you forget to use the  var   keyword to define a value within a function—even if it’s only used within the function—the value will be defined globally. var  foo = “new”; alert( foo == “new” ); // Omitting the var keyword reverts scope // of  foo  to global level function  badTest () {   foo = “bad news”; } badTest(); // Global  foo  now equals “bad news” alert( foo == “bad news” );
Scope:  Inner Functions Functions can be defined within one another Inner functions have access to the outer function’s variables and parameters. function  getRandomInt(max) {   var  randNum = Math.random() * max;   function  ceil() {   return  Math.ceil(randNum);   }   return  ceil();  // Notice that no arguments are passed } // Alert random number between 1 and 5 alert(getRandomInt(5));
Closures Inner functions maintain the scope they enjoyed when their parent function was called—even  after  the parent function has terminated. This allows you to effectively pass variables to functions that may not be called for some time.
Closures function  delayedAlert (message, delay) {   // Set an enclosed callback   setTimeout(  function  () {   // Use  message  variable passed to outer function   alert(message);   }, delay); } // Display a message with a 5 second delay delayedAlert(“Refresh”, 5000);
Context Your code will always be running within the  context  of another object Context is maintained through the use of the  this  variable. function   increment() {   this .x =  this .x || 0;   return   this .x++; }; alert( increment() == 0 ); alert( increment() == 1 );
Context var  myObject = {   set:  function  (newVal) {  this .val = newVal; } }; alert( myObject.val ==  null  );  //  val  property not set yet myObject.set(“Refresh”); alert( myObject.val == “Refresh” ); //  val  equals “Refresh” // Change the context of  set()  to the window object  window.set = myObject.set;  window.set( “Refresh Jacksonville” ); alert( myObject.val == “Refresh” ); alert( window.val == “Refresh Jacksonville” );
Context:  Changing Contexts JavaScript provides two handy functions for executing a function within the context of another function: call( ) apply( )
Context:  Changing Contexts Using  call()  — Arguments passed by name // Simple function to change the color style of a node function  changeColor (newColor) {   this .style.color = newColor; } // window.changeColor has no  style  property, so call fails changeColor( “red” ); // Grab the DOM node with the id “required” var  reqField = document.getElementById( “required” ); // Call changeColor() within reqField’s context changeColor.call( reqField, “red” );
Context:  Changing Contexts Using  apply()  — Arguments passed as an array // Simple function to change the color style of a node function  changeColor (newColor) {   this .style.color = newColor; } // Set the text color of the body element function setBodyTextColor () {   changeColor.apply( document.body,  arguments  ); } setBodyTextColor( “black” );
Constructors and methods
Object Oriented Programming Now let’s apply all of this information to a more classical view of OOP in JavaScript: Constructors  Object Methods Public Private Privileged
About Objects Almost everything written in JavaScript is an object Objects can be though of as a collection of properties—much like a  hash  in other languages JavaScript doesn’t have a concept of classes like other object-oriented languages Classes are simulated using a concept called  prototypal inheritance
Constructors Like other languages, JavaScript uses the  new   operator to create new instances of objects. // Create User object constructor function  User ( name ) {   this .name = name; } // Create a new instance of a User var  me = new User(“Bob”); // Alert new user’s name alert( me.name == “Bob” ); // Cannot call User directly alert( User.name ==  undefined  ); // window.name is undefined
Methods
Public Methods One way to create a public method—a function that can be freely reference by code outside your object—is to attach it to the object’s  prototype . An object’s  prototype  is a special property that acts as a base reference of your object.  This  prototype  object is copied and applied to all new instances of your object.
Public Methods // Our User object written a different way var  User =  function  (name) {   this .name = name; } // Add a public accessor method for name User. prototype .getName = function () {   return   this .name; } var  me =  new  User( “Bob” ); alert( me.getName() == “Bob” );
Private Methods Private methods are functions that are only accessible to methods  inside  your object and cannot be accessed by external code.
Private Methods // Our User object with some changes var  User =  function  (name) {   this .name = name;   function  welcome () {   alert( “Welcome back, ” +  this .name + “.”);   }   welcome(); } // Create a new User  var  me =  new  User( “Bob” );  // Alerts: “Welcome, Bob.” // Fails because welcome is not a public method me.welcome();
“ Privileged” Methods The term  privileged method  was coined by Douglas Crockford.  It is not a formal construct, but rather a technique. Privileged methods essentially have one foot in the door: Then can access private methods and values within the object They are also publicly accessible
“ Privileged” Methods // Our User object with some tweaks var  User =  function  (name, age) {   var  year = (new Date()).getFullYear() – age;   this .getYearBorn = function () {   return  year;   }; }; // Create a new User  var  me =  new  User( “Bob”, 28 );  // Access privileged method to access private  year  value alert( me.getYearBorn() == 1980 ); // Fails because  year  is private alert( me.year == null );
Grand Finale Using  Scope ,  Closures ,  Contexts , and what we’ve discussed about OOP, we can dynamically generate classes based on information supplied to the constructor.
Grand Finale // Our User object modified to accept an object of properties function  User (properties) {   // Loop through properties and create getter and setter methods   for  (  var  i  in  properties ) {  function  () {   this [“get” + i] =  function  () {   return  properties[i];   };   this [“set” + i] =  function  (val) {   properties[i] = val;   };   })(); } } // Create a new user, automatically creating get and set methods var  me =  new  User( {   name: “Bob”,   age: 28 });
Grand Finale // …continued // Note that  name  is private within  properties alert( me.name ==  null  ); // Access privileged  getname()  method alert( me.getname() == “Bob” ); // Use the dynamically generated setter  // to change the user’s age me.setage(21); alert( me.getage() == 21 );
 
References Pro JavaScript Techniques,   by John Resig Douglas Crockford’s  YUI Theater Presentations http://developer.yahoo.com/yui/theater

More Related Content

What's hot (20)

Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
Enrique Juan de Dios
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
Doeun KOCH
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
Prajwala Manchikatla
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
Robert Nyman
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
Brendan Eich
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
Stoyan Stefanov
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
mpnkhan
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
David Atchley
 
Prototype
PrototypePrototype
Prototype
Aditya Gaur
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange
 
Javascript
JavascriptJavascript
Javascript
theacadian
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
hwilming
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
Brian Moschel
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
Doeun KOCH
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
Robert Nyman
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
Brendan Eich
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
mpnkhan
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
hwilming
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 

Similar to Object Oriented JavaScript (20)

6976.ppt
6976.ppt6976.ppt
6976.ppt
MuhammedSheriefHagra
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
Marjan Nikolovski
 
Advance JS and oop
Advance JS and oopAdvance JS and oop
Advance JS and oop
Abuzer Firdousi
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
Nicholas Jansma
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
Paweł Dorofiejczyk
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
Ivano Malavolta
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
Tarek Mahmud Apu
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
LearningTech
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Subramanyan Murali
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
Tran Khoa
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Julie Iskander
 
OSCON - ES6 metaprogramming unleashed
OSCON -  ES6 metaprogramming unleashedOSCON -  ES6 metaprogramming unleashed
OSCON - ES6 metaprogramming unleashed
Javier Arias Losada
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
scottw
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Alena Holligan
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
Zain Shaikh
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
David Jacobs
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
Leonardo Borges
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
Nicholas Jansma
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
LearningTech
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
Tran Khoa
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Julie Iskander
 
OSCON - ES6 metaprogramming unleashed
OSCON -  ES6 metaprogramming unleashedOSCON -  ES6 metaprogramming unleashed
OSCON - ES6 metaprogramming unleashed
Javier Arias Losada
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
scottw
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Alena Holligan
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
Zain Shaikh
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
David Jacobs
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
Leonardo Borges
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
Ad

Recently uploaded (20)

End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Ad

Object Oriented JavaScript

  • 1. Getting from Scripts to Applications Donald J. Sipe | Refresh Jacksonville | November 11 th 2008
  • 2. JavaScript We are here Pseudoclassical Inheritance Hello World!
  • 3. JavaScript What we’ll be talking about OOP Basics Scope Closures Context Appling to OOP Constructors Methods Public Private Privileged
  • 4. But First... Some handy tools Here are some handy things you might not know JavaScript can do: Object-literal notation Anonymous functions Binary assignment Dot-style and array-style access of properties
  • 5. Handy Tools Object Literal Notation— Makes JSON possible // The old way var myObject = new Object(); myObject.val = “test”; // Using object literal notation var myObject = { val: “test” };
  • 6. Handy Tools Object Literal Notation // The old way var myArray = new Array(1, 30, “Refresh”); // Using object literal notation var myArray = [1, 30, “Refresh”];
  • 7. Handy Tools Anonymous Functions In JavaScript, functions are treated as values, which means: Functions can be assigned to variables Functions can be passed as arguments to other functions
  • 8. Handy Tools Anonymous Functions // Using an anonymous function as an argument setTimeout( function () { alert( “Refresh” ); }, 1000 ); // Using a function as a variable var myFunc = function () { alert( “Refresh” ); }; setTimeout(myFunc, 1000);
  • 9. Handy Tools Anonymous Functions : Building a “scope bubble” Using an anonymous function to wrap code you don’t want in the global scope var globalVar = “Refresh”; // Global scope // Create a scope bubble ( function () { var privateVar = “Jacksonville”; alert( globalVar + “ ” + privateVar ); } )(); alert (privateVar == undefined );
  • 10. Handy Tools Binary Assignment Set a default value only if the variable doesn’t have a value yet // Traditional ternary assignment var myVar = myVar ? myVar : 0; // Binary assignment var myVar = myVal || 0;
  • 11. Handy Tools Dot-Style and Array-Style property access var sampleObj = { color: “blue”, width: “16px” }; // Traditional dot-style access alert( sampleObj.color == “blue” ); // Alternative array-style access alert( sampleObj[“width”] == “16px” );
  • 13. Scope Only functions have scope. Blocks ( if , while , for , switch ) do not. All variables are within the global scope unless they are defined within a function . All global variables actually become properties of the window object When variables are not declared using the var keyword, they decared globally.
  • 14. Scope var foo = “orig”; // foo is now a global variable if ( true ) { foo = “new”; // Global foo now equals “new” } // create function to modify its own foo variable function test () { var foo = “old”; } test(); alert( foo == “new” ); // Global foo still equals “new”
  • 15. Scope If you forget to use the var keyword to define a value within a function—even if it’s only used within the function—the value will be defined globally. var foo = “new”; alert( foo == “new” ); // Omitting the var keyword reverts scope // of foo to global level function badTest () { foo = “bad news”; } badTest(); // Global foo now equals “bad news” alert( foo == “bad news” );
  • 16. Scope: Inner Functions Functions can be defined within one another Inner functions have access to the outer function’s variables and parameters. function getRandomInt(max) { var randNum = Math.random() * max; function ceil() { return Math.ceil(randNum); } return ceil(); // Notice that no arguments are passed } // Alert random number between 1 and 5 alert(getRandomInt(5));
  • 17. Closures Inner functions maintain the scope they enjoyed when their parent function was called—even after the parent function has terminated. This allows you to effectively pass variables to functions that may not be called for some time.
  • 18. Closures function delayedAlert (message, delay) { // Set an enclosed callback setTimeout( function () { // Use message variable passed to outer function alert(message); }, delay); } // Display a message with a 5 second delay delayedAlert(“Refresh”, 5000);
  • 19. Context Your code will always be running within the context of another object Context is maintained through the use of the this variable. function increment() { this .x = this .x || 0; return this .x++; }; alert( increment() == 0 ); alert( increment() == 1 );
  • 20. Context var myObject = { set: function (newVal) { this .val = newVal; } }; alert( myObject.val == null ); // val property not set yet myObject.set(“Refresh”); alert( myObject.val == “Refresh” ); // val equals “Refresh” // Change the context of set() to the window object window.set = myObject.set; window.set( “Refresh Jacksonville” ); alert( myObject.val == “Refresh” ); alert( window.val == “Refresh Jacksonville” );
  • 21. Context: Changing Contexts JavaScript provides two handy functions for executing a function within the context of another function: call( ) apply( )
  • 22. Context: Changing Contexts Using call() — Arguments passed by name // Simple function to change the color style of a node function changeColor (newColor) { this .style.color = newColor; } // window.changeColor has no style property, so call fails changeColor( “red” ); // Grab the DOM node with the id “required” var reqField = document.getElementById( “required” ); // Call changeColor() within reqField’s context changeColor.call( reqField, “red” );
  • 23. Context: Changing Contexts Using apply() — Arguments passed as an array // Simple function to change the color style of a node function changeColor (newColor) { this .style.color = newColor; } // Set the text color of the body element function setBodyTextColor () { changeColor.apply( document.body, arguments ); } setBodyTextColor( “black” );
  • 25. Object Oriented Programming Now let’s apply all of this information to a more classical view of OOP in JavaScript: Constructors Object Methods Public Private Privileged
  • 26. About Objects Almost everything written in JavaScript is an object Objects can be though of as a collection of properties—much like a hash in other languages JavaScript doesn’t have a concept of classes like other object-oriented languages Classes are simulated using a concept called prototypal inheritance
  • 27. Constructors Like other languages, JavaScript uses the new operator to create new instances of objects. // Create User object constructor function User ( name ) { this .name = name; } // Create a new instance of a User var me = new User(“Bob”); // Alert new user’s name alert( me.name == “Bob” ); // Cannot call User directly alert( User.name == undefined ); // window.name is undefined
  • 29. Public Methods One way to create a public method—a function that can be freely reference by code outside your object—is to attach it to the object’s prototype . An object’s prototype is a special property that acts as a base reference of your object. This prototype object is copied and applied to all new instances of your object.
  • 30. Public Methods // Our User object written a different way var User = function (name) { this .name = name; } // Add a public accessor method for name User. prototype .getName = function () { return this .name; } var me = new User( “Bob” ); alert( me.getName() == “Bob” );
  • 31. Private Methods Private methods are functions that are only accessible to methods inside your object and cannot be accessed by external code.
  • 32. Private Methods // Our User object with some changes var User = function (name) { this .name = name; function welcome () { alert( “Welcome back, ” + this .name + “.”); } welcome(); } // Create a new User var me = new User( “Bob” ); // Alerts: “Welcome, Bob.” // Fails because welcome is not a public method me.welcome();
  • 33. “ Privileged” Methods The term privileged method was coined by Douglas Crockford. It is not a formal construct, but rather a technique. Privileged methods essentially have one foot in the door: Then can access private methods and values within the object They are also publicly accessible
  • 34. “ Privileged” Methods // Our User object with some tweaks var User = function (name, age) { var year = (new Date()).getFullYear() – age; this .getYearBorn = function () { return year; }; }; // Create a new User var me = new User( “Bob”, 28 ); // Access privileged method to access private year value alert( me.getYearBorn() == 1980 ); // Fails because year is private alert( me.year == null );
  • 35. Grand Finale Using Scope , Closures , Contexts , and what we’ve discussed about OOP, we can dynamically generate classes based on information supplied to the constructor.
  • 36. Grand Finale // Our User object modified to accept an object of properties function User (properties) { // Loop through properties and create getter and setter methods for ( var i in properties ) { function () { this [“get” + i] = function () { return properties[i]; }; this [“set” + i] = function (val) { properties[i] = val; }; })(); } } // Create a new user, automatically creating get and set methods var me = new User( { name: “Bob”, age: 28 });
  • 37. Grand Finale // …continued // Note that name is private within properties alert( me.name == null ); // Access privileged getname() method alert( me.getname() == “Bob” ); // Use the dynamically generated setter // to change the user’s age me.setage(21); alert( me.getage() == 21 );
  • 38.  
  • 39. References Pro JavaScript Techniques, by John Resig Douglas Crockford’s YUI Theater Presentations http://developer.yahoo.com/yui/theater