SlideShare a Scribd company logo
Object-Oriented  JavaScript Stoyan Stefanov, Yahoo! Inc. Beijing, Dec 6 th , 2008
About the presenter Yahoo! Performance YSlow 2.0 smush.it  tool phpied.com  blog
First off…  the Firebug console
Firebug console as a learning tool
Console features Inspect the contents of objects by clicking on them Tab auto-complete, a.k.a cheatsheet Arrows ↑ and ↓ Fiddle with any page
Any page
Fiddle
Objects
JavaScript !== Java C-like syntax   Classes  
Data types A. Primitive: number –  1 ,  3 ,  1001 ,  11.12 ,  2e+3 string –  "a" ,  "stoyan" ,  "0" boolean –  true  |  false null undefined B. Objects everything else…
Objects hash tables  key: value
A simple object var  obj = {}; obj.name =  'my object' ; obj.shiny =  true ;
A simple object var  obj =  { shiny:  true , isShiny:  function () { return   this .shiny; } } ; obj.isShiny();  // true
Methods When a property is a function we can call it a method
Object literal notation Key-value pairs Comma-delimited Wrapped in curly braces {a: 1, b: "test"}
Arrays Arrays are objects too Auto-increment properties Some useful methods
Arrays >>>  var  a = [1,3,2]; >>> a[0] 1 >>>  typeof  a "object"
Array literal notation var  array = [  "Square" , "brackets" ,   "wrap" ,   "the" ,   "comma-delimited" , "elements" ];
JSON Object literals + array literals JavaScript Object Notation {"num":  1 , "str":  "abc" ,  "arr": [ 1 , 2 , 3 ]}
Constructors
Functions functions are objects they have properties they have methods can be copied, deleted, augmented... special feature: invokable
Function function  say(what) { return  what; }
Function var  say =  function (what) { return  what; } ;
Function var  say =  function   say (what) { return  what; } ;
Functions are objects >>> say.length 1 >>> say.name "boo"
Functions are objects >>>  var  tell = say; >>> tell( "doodles" ) "doodles" >>> tell. call ( null ,  "moo!" ); "moo!"
Return values All functions always return a value
Return values If a function doesn’t return a value explicitly, it returns  undefined
Return values Functions can return objects, including other functions
Constructors
Constructor functions when invoked with  new , functions return an object known as  this   you can modify  this  before it’s returned
Constructor functions var  Person =  function (name) { this .name = name; this .getName = function() { return  this .name; }; };
Using the constructor var  me =  new  Person( "Stoyan" ); me.getName();  // "Stoyan"
Constructors… …  are just functions
A naming convention M yConstructor m yFunction
constructor  property >>>  function  Person(){}; >>>  var  jo =  new  Person(); >>> jo. constructor  === Person true
constructor  property >>>  var  o = {}; >>> o. constructor  === Object true >>> [1,2]. constructor  === Array true
Built-in constructors Object Array Function RegExp Number String Boolean Date Error, SyntaxError, ReferenceError…
Use this Not that var o = {}; var o = new Object(); var a = []; var a = new Array(); var re = /[a-z]/gmi; var re = new RegExp( '[a-z]', 'gmi'); var fn = function(a, b){ return a + b; } var fn = new Function( 'a, b','return a+b');
Prototype
Prototype… …  is a property of the function objects
Prototype >>>  var  boo =  function (){}; >>>  typeof  boo. prototype "object"
Augmenting prototype >>> boo. prototype .a =  1 ; >>> boo. prototype .sayAh =  function (){};
Overwriting the prototype >>> boo. prototype  =  {a:  1 , b:  2 };
Use of the prototype The prototype is used when a function is called as a constructor
Prototype usage var  Person =  function (name) { this .name = name; }; Person. prototype .say =  function (){ return this .name; };
Prototype usage >>>  var  dude =  new  Person( 'dude' ); >>> dude.name; "dude" >>> dude.say(); "dude"
Prototype usage say()  is a property of the  prototype  object but it behaves as if it's a property of the dude object can we tell the difference?
Own properties vs. prototype’s >>> dude. hasOwnProperty ( 'name' ); true >>> dude. hasOwnProperty ( 'say' ); false
isPrototypeOf() >>> Person. prototype . isPrototypeOf (dude); true >>>  Object . prototype . isPrototypeOf (dude); true
__proto__ The objects have a secret link to the prototype of the constructor that created them __proto__ is not directly exposed in all browsers
__proto__ >>> dude.__proto__. hasOwnProperty ( 'say' ) true >>> dude. prototype ???  // Trick question >>> dude.__proto__.__proto__. hasOwnProperty ( 'toString' ) true
Prototype chain
It’s a live chain >>>  typeof  dude.numlegs "undefined" >>> Person. prototype .numlegs =  2 ; >>> dude.numlegs 2
Inheritance
Parent constructor function  NormalObject() { this .name =  'normal' ; this .getName =  function () {   return   this .name;  }; }
Child constructor function  PreciousObject(){  this .shiny =  true ;  this .round =  true ;  }
The inheritance PreciousObject. prototype  =  new  NormalObject();
A child object var  crystal_ball =  new  PreciousObject(); crystal_ball.name =  'Crystal Ball.' ; crystal_ball.round;  // true crystal_ball.getName();  // "Crystal Ball."
Inheritance by copying
Two objects var  shiny = {  shiny:  true ,  round:  true   };  var  normal = {  name:  'name me' ,  getName:  function () { return this .name;  } };
extend() function  extend(parent, child) {  for  ( var  i  in  parent) {  child[i] = parent[i];  }  }
Inheritance extend(normal, shiny); shiny.getName();  // "name me"
Prototypal inheritance
Beget object function  object(o) { function  F(){} F. prototype  = o; return new  F(); }
Beget object >>>  var  parent = {a:  1 }; >>>  var  child = object(parent); >>> child.a; 1 >>> child. hasOwnProperty (a); false
Wrapping up…
Objects Everything is an object (except a few primitive types) Objects are hashes Arrays are objects
Functions Functions are objects Only invokable Methods: call(), apply() Properties: length, name, prototype
Prototype Property of the function objects It’s an object  Useful with Constructor functions
Constructor A function meant to be called with  new Returns an object
Class No such thing in JavaScript
Inheritance Class ical Prototypal By copying …  and many other variants
Stoyan Stefanov, http://phpied.com [email_address]

More Related Content

PPT
Object Oriented JavaScript
PPTX
Understanding Object Oriented Javascript - Coffee@DBG June
PPT
Advanced JavaScript
PPT
Advanced Javascript
PPT
Advanced JavaScript
PDF
Object Oriented Programming in JavaScript
PPTX
Advanced JavaScript
PDF
Object Oriented JavaScript
Object Oriented JavaScript
Understanding Object Oriented Javascript - Coffee@DBG June
Advanced JavaScript
Advanced Javascript
Advanced JavaScript
Object Oriented Programming in JavaScript
Advanced JavaScript
Object Oriented JavaScript

What's hot (20)

PDF
Java Script Best Practices
PDF
JavaScript Basics and Best Practices - CC FE & UX
PPT
JavaScript In Object Oriented Way
PDF
Advanced javascript
PDF
JavaScript - From Birth To Closure
PPTX
Object Oriented Programming In JavaScript
PPT
JavaScript Basics
PPTX
Javascript basics for automation testing
PPT
A Deeper look into Javascript Basics
PDF
Powerful JavaScript Tips and Best Practices
PDF
Prototype
PDF
Core concepts-javascript
PPTX
5 Tips for Better JavaScript
PPTX
Javascript Prototype Visualized
PDF
Basics of JavaScript
ODP
Javascript
PDF
JavaScript Patterns
PDF
Fundamental JavaScript [UTC, March 2014]
KEY
JavaScript Growing Up
PDF
Ten useful JavaScript tips & best practices
Java Script Best Practices
JavaScript Basics and Best Practices - CC FE & UX
JavaScript In Object Oriented Way
Advanced javascript
JavaScript - From Birth To Closure
Object Oriented Programming In JavaScript
JavaScript Basics
Javascript basics for automation testing
A Deeper look into Javascript Basics
Powerful JavaScript Tips and Best Practices
Prototype
Core concepts-javascript
5 Tips for Better JavaScript
Javascript Prototype Visualized
Basics of JavaScript
Javascript
JavaScript Patterns
Fundamental JavaScript [UTC, March 2014]
JavaScript Growing Up
Ten useful JavaScript tips & best practices
Ad

Viewers also liked (18)

PDF
Javascript Best Practices
KEY
Object oriented javascript
PPT
ООП в JavaScript
PDF
Turning to the client side
ODP
JavaScript global object, execution contexts & closures
PPTX
Grunt
ODP
Untitled 1
PDF
The Wearable Machine
DOCX
These companies are very good eficientando their innovation processes
PPT
Making Beer Money from your Travel Blog
PDF
طباعة التقرير - إختبر درجة إبداعك احمد الذهب
DOCX
Grandmas Recipes by Wendy Pang
DOCX
Matriz de valoracion pid y aamtic
PDF
Hakukoneet ja mittaristo #digisawotta
DOCX
Mapa conceptual. GESTIÓN DE PROYECTO
PDF
Plan lector 4 todos somos iguales
PPTX
5 pen pc tecnology
PDF
How can communities shape economic development and create quality jobs
Javascript Best Practices
Object oriented javascript
ООП в JavaScript
Turning to the client side
JavaScript global object, execution contexts & closures
Grunt
Untitled 1
The Wearable Machine
These companies are very good eficientando their innovation processes
Making Beer Money from your Travel Blog
طباعة التقرير - إختبر درجة إبداعك احمد الذهب
Grandmas Recipes by Wendy Pang
Matriz de valoracion pid y aamtic
Hakukoneet ja mittaristo #digisawotta
Mapa conceptual. GESTIÓN DE PROYECTO
Plan lector 4 todos somos iguales
5 pen pc tecnology
How can communities shape economic development and create quality jobs
Ad

Similar to Beginning Object-Oriented JavaScript (20)

KEY
Javascript tid-bits
PPTX
Object Oriented JavaScript
PPT
Advanced Javascript
PPT
Advanced Javascript
PPTX
Ajaxworld
PDF
Js objects
PPTX
Typescript barcelona
PPT
Javascript Object Oriented Programming
PPTX
OO in JavaScript
PDF
JavaScript Survival Guide
PPTX
Javascript Objects Deep Dive
PPTX
WEB222-lecture-4.pptx
PPTX
Object oriented javascript
PPTX
JavsScript OOP
PDF
JavaScript Essentials
PDF
JavaScript Core
PDF
The many facets of code reuse in JavaScript
PPTX
Understanding-Objects-in-Javascript.pptx
PPTX
Ian 20150116 java script oop
PPTX
4front en
Javascript tid-bits
Object Oriented JavaScript
Advanced Javascript
Advanced Javascript
Ajaxworld
Js objects
Typescript barcelona
Javascript Object Oriented Programming
OO in JavaScript
JavaScript Survival Guide
Javascript Objects Deep Dive
WEB222-lecture-4.pptx
Object oriented javascript
JavsScript OOP
JavaScript Essentials
JavaScript Core
The many facets of code reuse in JavaScript
Understanding-Objects-in-Javascript.pptx
Ian 20150116 java script oop
4front en

More from Stoyan Stefanov (20)

PDF
Reactive JavaScript
PPTX
YSlow hacking
PPTX
Liking performance
PPTX
JavaScript Performance Patterns
PPTX
JavaScript performance patterns
PPTX
High Performance Social Plugins
PDF
Social Button BFFs
PPTX
JavaScript навсякъде
PPTX
JavaScript is everywhere
PDF
JavaScript shell scripting
PDF
JavaScript for PHP developers
PDF
WPO @ PubCon 2010
PDF
Progressive Downloads and Rendering - take #2
PDF
Progressive Downloads and Rendering
PDF
Performance patterns
PDF
Voices that matter: High Performance Web Sites
PDF
Psychology of performance
PPT
3-in-1 YSlow
PDF
CSS and image optimization
PPT
High-performance DOM scripting
Reactive JavaScript
YSlow hacking
Liking performance
JavaScript Performance Patterns
JavaScript performance patterns
High Performance Social Plugins
Social Button BFFs
JavaScript навсякъде
JavaScript is everywhere
JavaScript shell scripting
JavaScript for PHP developers
WPO @ PubCon 2010
Progressive Downloads and Rendering - take #2
Progressive Downloads and Rendering
Performance patterns
Voices that matter: High Performance Web Sites
Psychology of performance
3-in-1 YSlow
CSS and image optimization
High-performance DOM scripting

Recently uploaded (20)

PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Encapsulation theory and applications.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPT
Teaching material agriculture food technology
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Spectral efficient network and resource selection model in 5G networks
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Network Security Unit 5.pdf for BCA BBA.
20250228 LYD VKU AI Blended-Learning.pptx
NewMind AI Monthly Chronicles - July 2025
Encapsulation theory and applications.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Teaching material agriculture food technology
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Per capita expenditure prediction using model stacking based on satellite ima...
Advanced methodologies resolving dimensionality complications for autism neur...
Building Integrated photovoltaic BIPV_UPV.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf

Beginning Object-Oriented JavaScript