advanced javascript closures prototypes inheritance n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Advanced JavaScript: closures, prototypes, inheritance PowerPoint Presentation
Download Presentation
Advanced JavaScript: closures, prototypes, inheritance

Loading in 2 Seconds...

play fullscreen
1 / 113

Advanced JavaScript: closures, prototypes, inheritance - PowerPoint PPT Presentation


  • 113 Views
  • Uploaded on

Advanced JavaScript: closures, prototypes, inheritance. Stoyan Stefanov Ajax Experience, Boston 2008. About the presenter. Yahoo! performance team member YSlow 2.0 architect, dev Book author, open-source contributor Blog: http://phpied.com.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Advanced JavaScript: closures, prototypes, inheritance' - delling


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
advanced javascript closures prototypes inheritance

Advanced JavaScript:closures, prototypes, inheritance

Stoyan Stefanov

Ajax Experience, Boston 2008

about the presenter
About the presenter

Yahoo! performance team member

YSlow 2.0 architect, dev

Book author, open-source contributor

Blog: http://phpied.com

firebug console
Firebug console…

Inspect the contents of objects by clicking on them

Tab auto-complete, a.k.a cheatsheet

Arrows ↑ and↓

Fiddle with any page

javascript data types
JavaScript data types

primitive and objects

number

string

boolean

undefined

null

what s an object
What’s an object?

a hash of key => value pairs

if a key (property) happens to be a function, we can call it a method

what s an object1
What’s an object?

var obj = {

shiny: true,

isShiny: function() {

returnthis.shiny;

}

};

obj.isShiny(); // true

object literal notation
Object literal notation

{ Wrapped in curly braces }

,-delimited properties

key:value pairs

var obj = {a: 1, "b c d": 2};

arrays1
Arrays

arrays are also objects

auto-incremented properties

arrays2
Arrays

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

>>> a[0]

1

>>> typeof a

"object"

arrays3
Arrays

array objects also get some cool properties...

>>> a.length

3

...and methods

>>> a.sort()

>>> a.join(' < ')

"1 < 2 < 3"

array literal notation
Array literal notation

var array = [

"Square", "brackets",

"wrap", "the",

"comma-delimited",

"elements"

];

slide18
JSON

JavaScript Object Notation

Uses object and array literals

Quotes required for properties

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

functions1
Functions

functions are objects

they have properties

they have methods

can de copied, deleted, augmented...

special feature: invokable

functions2
Functions

function boo(what) {

return what;

}

or

var boo = function(what) {

return what;

};

functions3
Functions

function boo(what) {

return what;

}

or

var boo = functionbootoo(what) {

return what;

};

functions are objects
Functions are objects

>>> boo.length

1

>>> boo.name

"bootoo"

functions are objects1
Functions are objects

>>> var foo = boo;

>>> foo("doodles")

"doodles"

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

"moo!"

return value
Return value

all functions return a value

if they don't explicitly, they return undefined implicitly

functions can return other functions

constructors1
Constructors

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

you have a chance of modifying this before it's returned

you can also return some other object

constructor functions
Constructor functions

var Person = function(name) {

this.name = name;

this.speaks = 'fr';

this.say = function() {

return "Je m'appelle " + this.name;

};

};

an object created with constructor
An object created with constructor

>>> var julien = new Person("Julien");

>>> julien.say();

"Je m'appelle Julien"

constructor s return value
Constructor’s return value

var Person = function(){

this.first = "Bruce";

return {last: "Wayne"};

};

>>> typeof new Person().first

"undefined"

>>> new Person().last

"Wayne"

constructor s return value1
Constructor’s return value

var Person = function(){

this.first = "Bruce";

return"Batman";

};

>>> new Person().first

"Bruce"

naming convention
Naming convention

MyConstructor

myFunction

constructor property
constructor property

>>> function Person(){};

>>> var jo = new Person();

>>> jo.constructor === Person

true

constructor property1
constructor property

>>> var o = {};

>>> o.constructor === Object

true

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

true

built in constructor functions
Built-in constructor functions

Object

Array

Function

RegExp

Number

String

Boolean

Date

Error, SyntaxError, ReferenceError…

wrapper objects vs primitive
Wrapper objects vs. primitive

>>> typeof new Number(1)

"object"

>>> typeof1

"number"

primitives can act as objects
Primitives can act as objects

>>> "test".length

4

>>> (123.456).toFixed(2)

"123.46"

prototype1
prototype

a property of the function objects

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

>>> typeof boo.prototype

"object"

prototypes can be augmented
Prototypes can be augmented

>>> boo.prototype.a = 1;

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

prototypes can be overwritten
Prototypes can be overwritten

>>> boo.prototype = {a: 1, b: 2};

how is the prototype used
How is the prototype used?

when a function is invoked as a constructor

var Person = function(name) {

this.name = name;

};

Person.prototype.say = function() {

return this.name;

}

how is the prototype used1
>>> var dude = new Person('dude');

>>> dude.name;

"dude"

>>> dude.say();

"dude"

How is the prototype used?
how is the prototype used2
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?

How is the prototype used?
own properties vs prototype s
Own properties vs. prototype’s

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

true

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

false

isprototypeof
isPrototypeOf()

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

true

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

true

proto
__proto__

I, the dude, have a secret link to the prototype of the constructor that created me

__proto__ is not directly exposed in all browsers

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

true

>>> dude.prototype

??? // Trick question

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

true

__proto__
it s alive
It’s alive!

>>> typeof dude.numlegs

"undefined"

>>> Person.prototype.numlegs = 2;

>>> dude.numlegs

2

inheritance via the prototype
Inheritance via the prototype

>>> var Dad = function(){this.family = "Stefanov";};

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

>>> Kid.prototype = new Dad();

>>> var billy = new Kid();

>>> billy.family

"Stefanov"

inherit one more time
Inherit one more time

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

>>> GrandKid.prototype = billy;

>>> var jill = new GrandKid();

>>> jill.family

"Stefanov"

inheritance1
Inheritance…

>>> jill.hasOwnProperty('family')

false

>>> jill.__proto__.hasOwnProperty('family')

false

>>> jill.__proto__.__proto__.hasOwnProperty('family')

true

inheritance2
Inheritance…

>>> billy.family = 'Idol';

>>> jill.family;

'Idol'

>>> jill.__proto__.hasOwnProperty('family');

true

>>> delete billy.family;

>>> jill.family;

'Stefanov'

side effect
Side effect…

>>> billy.constructor === Kid

false

>>> billy.constructor === Dad

true

side effect easy to solve
Side effect… easy to solve

reset after inheritance

>>> Kid.prototype.constructor = Kid;

>>> GrandKid.prototype.constructor = GrandKid;

isprototypeof1
isPrototypeOf

>>> billy.isPrototypeOf(jill)

true

>>> Kid.prototype.isPrototypeOf(jill)

true

instanceof
instanceof

>>> jill instanceof GrandKid

true

>>> jill instanceof Kid

true

>>> jill instanceof Dad

true

classes
Classes?

There are no classes in JavaScript

Objects inherit from objects

classical inheritance is when we think of constructors as if they were classes

classical inheritance
Classical inheritance

function Parent(){this.name = 'parent';}

Parent.prototype.getName = function(){return this.name;};

function Child(){}

inherit(Child, Parent);

option 1
Option 1

function inherit(C, P) {

C.prototype = new P();

}

option 2
Option 2

function inherit(C, P) {

C.prototype = P.prototype;

}

option 3
Option 3

function inherit(C, P) {

var F = function(){};

F.prototype = P.prototype;

C.prototype = new F();

}

option 3 super
Option 3 + super

function inherit(C, P) {

var F = function(){};

F.prototype = P.prototype;

C.prototype = new F();

C.uber = P.prototype;

}

option 3 super constructor reset
Option 3 + super + constructor reset

function inherit(C, P) {

var F = function(){};

F.prototype = P.prototype;

C.prototype = new F();

C.uber = P.prototype; // super

C.prototype.constructor = C; // reset

}

inheritance by copying properties
Inheritance by copying properties

After all, inheritance is all about code reuse

function extend(parent) {

var i, child = {};

for (i in parent) {

child[i] = parent[i];

}

return child;

}

inheritance by copying
Inheritance by copying…

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

>>> var child = extend(parent);

>>> child.a

1

inheritance by copying1
Inheritance by copying…

This was a shallow copy

you can make a deep copy using recursion

mixins / multiple inheritance

prototypal inheritance
Prototypal inheritance

as suggested by Douglas Crockford

no class-like constructors involved

objects inherit from objects

via the prototype

prototypal inheritance1
Prototypal inheritance

function object(o) {

function F(){}

F.prototype = o;

return new F();

}

prototypal inheritance2
Prototypal inheritance

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

>>> var child = object(parent);

>>> child.a;

1

>>> child.hasOwnProperty(a);

false

no block scope
No block scope

>>> if (true) {var inside_block = 1;}

>>> inside_block

1

function scope
Function scope

function boo() {

var inboo = true;

}

global namespace
Global namespace

every variable is global unless it's in a function and is declared with var

global namespace should be kept clean to avoid naming collisions

function scope can help

self executable functions for one off tasks
Self-executable functions for one-off tasks

(function(){

var a = 1;

var b = 2;

alert(a + b);

})()

closure example 1
Closure example #1

function outer(){

var local = 1;

returnfunction(){

return local;

};

}

example 1
example #1…

>>> var inner = outer()

>>> inner()

1

closure example 2
Closure example #2

var inner;

function outer(){

var local = 1;

inner = function(){

return local;

};

}

example 2
example #2…

>>> typeof inner

"undefined"

>>> outer()

>>> inner()

1

closure example 3
Closure example #3

function makePlus(arg) {

var n = function(){

return arg;

};

arg++;

return n;

}

example 3
example #3…

>>> var getValue = makePlus(1234);

>>> getValue()

1235

closure 4 in a loop
Closure #4 – in a loop

function make() {

var i, a = [];

for(i = 0; i < 3; i++) {

a[i] = function(){

return i;

}

}

return a;

}

closure 4 test oops
Closure #4 test - oops

>>> var funcs = make();

>>> funcs[0]();

3

>>> funcs[1]();

3

>>> funcs[2]();

3

closure 4 corrected
Closure #4 – corrected

function make() {

var i, a = [];

for(i = 0; i < 3; i++) {

a[i] = (function(local){

returnfunction(){return local;}

})(i)

}

return a;

}

getter setter
Getter/Setter

var getValue, setValue;

(function() {

var secret = 0;

getValue = function(){

return secret;

};

setValue = function(v){

secret = v;

};

})()

// usage

>>> getValue()

0

>>> setValue(123)

>>> getValue()

123

iterator
Iterator

function setup(x) {

var i = 0;

returnfunction(){

return x[i++];

};

}

iterator usage
Iterator usage

>>> var next = setup(['a', 'b', 'c']);

>>> next()

'a'

>>> next()

'b'

loop through dom elements wrong
Loop through DOM elements - wrong

// all elements will alert 5

for (var i = 1; i < 5; i++ ){

document.getElementById('btn'+i).onclick =

function(){

alert(i);

};

}

loop through dom elements correct
Loop through DOM elements - correct

// first element alerts 1, second 2,...

for (var i = 1; i < 5; i++ ){

document.getElementById('btn'+i).onclick =

(function(i){

return function(){alert(i);};

})(i)

}

wrapping up
Wrapping up…

How to tell what’s going on?

typeof, instanceof, isPrototypeOf()…

typeof variable
>>> typeofvariable

typeof is an operator, not a function

Not typeof(variable) even if it works

Returns a string, one of:

"string", "number", "boolean",

"undefined", "object", "function"

typeof
typeof

if (typeof whatever === "undefined") {

// whatever is not defined

}

if (whatever == undefined) {

// hmm, not so sure

}

obj instanceof myconstructor
>>> obj instanceofMyConstructor

Not instanceof()

Returns true | false

true for all constructors up the chain

obj constructor
>>> obj.constructor

Points to the constructor function used to create this obj

obj isprototypeof child obj
>>> obj.isPrototypeOf(child_obj)

Respects the prototype chain

obj hasownproperty prop
>>> obj.hasOwnProperty("prop")

Own properties vs. properties of the prototype

obj propertyisenumerable prop
obj.propertyIsEnumerable("prop")

Will it show up in a for-in loop

Caution: enumerable properties of the prototype will return false but still show up in the for-in loop

wrapping up1
Wrapping up…

What did we learn today?

objects1
Objects

JavaScript has a few primitive types, everything else is an object

Objects are hashes

Arrays are objects

functions4
Functions

Functions are objects, only invokable

call() and apply() methods

prototype property

prototype2
Prototype

Functions have a prototype property which is an object

Useful with Constructor functions

constructor
Constructor

A function meant to be called with new

Returns an object

class
Class

No such thing in JavaScript

inheritance3
Inheritance

Prototypal

Classical

… and approximately 101 other ways and variations

scope1
Scope

Lexical function scope

closure
Closure

When a variable leaves its function scope

thank you
Thank you!

Stoyan Stefanov

http://www.phpied.com