You are on page 1of 74

Object-Oriented

JavaScript
Stoyan Stefanov, Yahoo! Inc.
Beijing, Dec 6th, 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 doesnt 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 its
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
MyConstructor
myFunction
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){ var fn = new Function(


return a + b; '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.
prototypes

>>> 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
Its 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
Its 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
Classical
Prototypal
By copying
and many other variants
Stoyan Stefanov, http://phpied.com
stoyan@yahoo-inc.com

You might also like