beginning object-oriented javascript

74
Object-Oriented JavaScript Stoyan Stefanov, Yahoo! Inc. Beijing, Dec 6 th , 2008

Upload: stoyan-stefanov

Post on 08-Sep-2014

22.783 views

Category:

Technology


0 download

DESCRIPTION

Slides from my "Object-oriented JavaScript" presentation at CSDN (China Software Developers Network), Beijing, December 2008

TRANSCRIPT

Page 1: Beginning Object-Oriented JavaScript

Object-Oriented JavaScript

Stoyan Stefanov, Yahoo! Inc.Beijing, Dec 6th, 2008

Page 2: Beginning Object-Oriented JavaScript

About the presenter• Yahoo! Performance• YSlow 2.0• smush.it tool• phpied.com blog

Page 3: Beginning Object-Oriented JavaScript

First off… the Firebug console

Page 4: Beginning Object-Oriented JavaScript

Firebug console as a learning tool

Page 5: Beginning Object-Oriented JavaScript

Console features• Inspect the contents of objects by clicking on them

• Tab auto-complete, a.k.a cheatsheet• Arrows ↑ and ↓• Fiddle with any page

Page 6: Beginning Object-Oriented JavaScript

Any page

Page 7: Beginning Object-Oriented JavaScript

Fiddle

Page 8: Beginning Object-Oriented JavaScript

Objects

Page 9: Beginning Object-Oriented JavaScript

JavaScript !== Java

• C-like syntax • Classes

Page 10: Beginning Object-Oriented JavaScript

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…

Page 11: Beginning Object-Oriented JavaScript

Objects• hash tables • key: value

Page 12: Beginning Object-Oriented JavaScript

A simple object

var obj = {};

obj.name = 'my object';

obj.shiny = true;

Page 13: Beginning Object-Oriented JavaScript

A simple object

var obj = {

shiny: true,

isShiny: function() {

return this.shiny;

}

};

obj.isShiny(); // true

Page 14: Beginning Object-Oriented JavaScript

Methods• When a property is a functionwe can call it a method

Page 15: Beginning Object-Oriented JavaScript

Object literal notation

• Key-value pairs• Comma-delimited• Wrapped in curly braces

{a: 1, b: "test"}

Page 16: Beginning Object-Oriented JavaScript

Arrays• Arrays are objects too• Auto-increment properties• Some useful methods

Page 17: Beginning Object-Oriented JavaScript

Arrays

>>> var a = [1,3,2];

>>> a[0]

1

>>> typeof a

"object"

Page 18: Beginning Object-Oriented JavaScript

Array literal notation

var array = [

"Square",

"brackets",

"wrap",

"the",

"comma-delimited",

"elements"

];

Page 19: Beginning Object-Oriented JavaScript

JSON• Object literals + array literals• JavaScript Object Notation

{"num": 1, "str": "abc", "arr": [1,2,3]}

Page 20: Beginning Object-Oriented JavaScript

Constructors

Page 21: Beginning Object-Oriented JavaScript

Functions• functions are objects• they have properties• they have methods• can be copied, deleted, augmented...

• special feature: invokable

Page 22: Beginning Object-Oriented JavaScript

Function

function say(what) {

return what;

}

Page 23: Beginning Object-Oriented JavaScript

Function

var say = function(what) {

return what;

};

Page 24: Beginning Object-Oriented JavaScript

Function

var say = function say(what) {

return what;

};

Page 25: Beginning Object-Oriented JavaScript

Functions are objects

>>> say.length

1

>>> say.name

"boo"

Page 26: Beginning Object-Oriented JavaScript

Functions are objects

>>> var tell = say;

>>> tell("doodles")

"doodles"

>>> tell.call(null, "moo!");

"moo!"

Page 27: Beginning Object-Oriented JavaScript

Return values

• All functions always return a value

Page 28: Beginning Object-Oriented JavaScript

Return values

• If a function doesn’t return a value explicitly, it returns undefined

Page 29: Beginning Object-Oriented JavaScript

Return values

• Functions can return objects, including other functions

Page 30: Beginning Object-Oriented JavaScript

Constructors

Page 31: Beginning Object-Oriented JavaScript

Constructor functions

• when invoked with new, functions return an object known as this

• you can modify this before it’s returned

Page 32: Beginning Object-Oriented JavaScript

Constructor functions

var Person = function(name) {

this.name = name;

this.getName = function() {

return this.name;

};

};

Page 33: Beginning Object-Oriented JavaScript

Using the constructor

var me = new Person("Stoyan");

me.getName(); // "Stoyan"

Page 34: Beginning Object-Oriented JavaScript

Constructors…… are just functions

Page 35: Beginning Object-Oriented JavaScript

A naming convention

• MyConstructor• myFunction

Page 36: Beginning Object-Oriented JavaScript

constructor property

>>> function Person(){};

>>> var jo = new Person();

>>> jo.constructor === Person

true

Page 37: Beginning Object-Oriented JavaScript

constructor property

>>> var o = {};

>>> o.constructor === Object

true

>>> [1,2].constructor === Array

true

Page 38: Beginning Object-Oriented JavaScript

Built-in constructors

• Object• Array• Function• RegExp• Number• String• Boolean• Date• Error, SyntaxError, ReferenceError…

Page 39: Beginning Object-Oriented JavaScript

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

Page 40: Beginning Object-Oriented JavaScript

Prototype

Page 41: Beginning Object-Oriented JavaScript

Prototype…… is a property of the function objects

Page 42: Beginning Object-Oriented JavaScript

Prototype

>>> var boo = function(){};

>>> typeof boo.prototype

"object"

Page 43: Beginning Object-Oriented JavaScript

Augmenting prototype

>>> boo.prototype.a = 1;

>>> boo.prototype.sayAh = function(){};

Page 44: Beginning Object-Oriented JavaScript

Overwriting the prototype

>>> boo.prototype =

{a: 1, b: 2};

Page 45: Beginning Object-Oriented JavaScript

Use of the prototype• The prototype is used when a function is called as a constructor

Page 46: Beginning Object-Oriented JavaScript

Prototype usage

var Person = function(name) {

this.name = name;

};

Person.prototype.say = function(){

return this.name;

};

Page 47: Beginning Object-Oriented JavaScript

Prototype usage

>>> var dude = new Person('dude');

>>> dude.name;

"dude"

>>> dude.say();

"dude"

Page 48: Beginning Object-Oriented JavaScript

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?

Page 49: Beginning Object-Oriented JavaScript

Own properties vs. prototype’s

>>> dude.hasOwnProperty('name');

true

>>> dude.hasOwnProperty('say');

false

Page 50: Beginning Object-Oriented JavaScript

isPrototypeOf()

>>> Person.prototype.isPrototypeOf(dude);

true

>>> Object.prototype.isPrototypeOf(dude);

true

Page 51: Beginning Object-Oriented JavaScript

__proto__• The objects have a secret link to the prototype of the constructor that created them

• __proto__ is not directly exposed in all browsers

Page 52: Beginning Object-Oriented JavaScript

__proto__

>>> dude.__proto__.hasOwnProperty('say')true

>>> dude.prototype??? // Trick question

>>> dude.__proto__.__proto__.hasOwnProperty('toString')

true

Page 53: Beginning Object-Oriented JavaScript

Prototype chain

Page 54: Beginning Object-Oriented JavaScript

It’s a live chain

>>> typeof dude.numlegs

"undefined"

>>> Person.prototype.numlegs = 2;

>>> dude.numlegs

2

Page 55: Beginning Object-Oriented JavaScript

Inheritance

Page 56: Beginning Object-Oriented JavaScript

Parent constructor

function NormalObject() {

this.name = 'normal';

this.getName = function() {

return this.name;

};

}

Page 57: Beginning Object-Oriented JavaScript

Child constructor

function PreciousObject(){

this.shiny = true;

this.round = true;

}

Page 58: Beginning Object-Oriented JavaScript

The inheritance

PreciousObject.prototype =

new NormalObject();

Page 59: Beginning Object-Oriented JavaScript

A child objectvar crystal_ball = new PreciousObject();

crystal_ball.name = 'Crystal Ball.';

crystal_ball.round; // true

crystal_ball.getName(); // "Crystal Ball."

Page 60: Beginning Object-Oriented JavaScript

Inheritance by copying

Page 61: Beginning Object-Oriented JavaScript

Two objectsvar shiny = { shiny: true, round: true }; var normal = { name: 'name me', getName: function() { return this.name; }};

Page 62: Beginning Object-Oriented JavaScript

extend()

function extend(parent, child) {

for (var i in parent) {

child[i] = parent[i];

}

}

Page 63: Beginning Object-Oriented JavaScript

Inheritance

extend(normal, shiny);

shiny.getName(); // "name me"

Page 64: Beginning Object-Oriented JavaScript

Prototypal inheritance

Page 65: Beginning Object-Oriented JavaScript

Beget object

function object(o) {

function F(){}

F.prototype = o;

return new F();

}

Page 66: Beginning Object-Oriented JavaScript

Beget object

>>> var parent = {a: 1};

>>> var child = object(parent);

>>> child.a;

1

>>> child.hasOwnProperty(a);

false

Page 67: Beginning Object-Oriented JavaScript

Wrapping up…

Page 68: Beginning Object-Oriented JavaScript

Objects• Everything is an object (except a few primitive types)

• Objects are hashes• Arrays are objects

Page 69: Beginning Object-Oriented JavaScript

Functions• Functions are objects• Only invokable• Methods: call(), apply()• Properties: length, name, prototype

Page 70: Beginning Object-Oriented JavaScript

Prototype• Property of the function objects• It’s an object • Useful with Constructor functions

Page 71: Beginning Object-Oriented JavaScript

Constructor• A function meant to be called with new

• Returns an object

Page 72: Beginning Object-Oriented JavaScript

Class• No such thing in JavaScript

Page 73: Beginning Object-Oriented JavaScript

Inheritance• Classical• Prototypal• By copying• … and many other variants

Page 74: Beginning Object-Oriented JavaScript

Stoyan Stefanov, http://[email protected]