Advanced JavaScript

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

2 comments

Comments 1 - 2 of 2 previous next Post a comment

  • + Lecteur Lecteur 2 weeks ago
    Thank you very much for this wonderful presentation. :-).
  • + guestefe29cf guestefe29cf 10 months ago
    Very good presentation!
Post a comment
Embed Video
Edit your comment Cancel

8 Favorites

Advanced JavaScript - Presentation Transcript

  1. Advanced JavaScript: closures, prototypes, inheritance Stoyan Stefanov Ajax Experience, Boston 2008
  2. About the presenter
    • Yahoo! performance team member
    • YSlow 2.0 architect, dev
    • Book author, open-source contributor
    • Blog: http:// phpied.com
  3. Before we start… Firebug console
  4. Firebug console is a learning tool
  5. Firebug console…
    • Inspect the contents of objects by clicking on them
    • Tab auto-complete, a.k.a cheatsheet
    • Arrows ↑ and↓
    • Fiddle with any page
  6. Any page…
  7. Fiddle…
  8. Objects
  9. JavaScript data types
    • primitive and objects
    • number
    • string
    • boolean
    • undefined
    • null
  10. 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
  11. What’s an object?
    • var obj = {
    • shiny: true ,
    • isShiny: function () {
    • return this .shiny;
    • }
    • } ;
    • obj.isShiny(); // true
  12. Object literal notation
    • { Wrapped in curly braces }
    • , -delimited properties
    • key : value pairs
    • var obj = {a: 1, "b c d": 2};
  13. Arrays
  14. Arrays
    • arrays are also objects
    • auto-incremented properties
  15. Arrays
    • >>> var a = [1,3,2];
    • >>> a[0]
    • 1
    • >>> typeof a
    • "object"
  16. Arrays
    • array objects also get some cool properties...
        • >>> a. length
        • 3
    • ...and methods
        • >>> a. sort ()
        • >>> a. join ( ' < ' )
        • &quot;1 < 2 < 3&quot;
  17. Array literal notation
    • var array = [
    • &quot;Square&quot; , &quot;brackets&quot; ,
    • &quot;wrap&quot; , &quot;the&quot; ,
    • &quot;comma-delimited&quot; ,
    • &quot;elements&quot;
    • ];
  18. JSON
    • JavaScript Object Notation
    • Uses object and array literals
    • Quotes required for properties
    • {&quot;num&quot;: 1 , &quot;str&quot;: &quot;abc&quot; , &quot;arr&quot;: [ 1 , 2 , 3 ]}
  19. Functions
  20. Functions
    • functions are objects
    • they have properties
    • they have methods
    • can de copied, deleted, augmented...
    • special feature: invokable
  21. Functions
    • function boo(what) {
    • return what;
    • }
    • or
    • var boo = function (what) {
    • return what;
    • } ;
  22. Functions
    • function boo(what) {
    • return what;
    • }
    • or
    • var boo = function bootoo (what) {
    • return what;
    • } ;
  23. Functions are objects
    • >>> boo.length
    • 1
    • >>> boo.name
    • &quot;bootoo&quot;
  24. Functions are objects
    • >>> var foo = boo;
    • >>> foo( &quot;doodles&quot; )
    • &quot;doodles&quot;
    • >>> foo. call ( null , &quot;moo!&quot; );
    • &quot;moo!&quot;
  25. Return value
    • all functions return a value
    • if they don't explicitly, they return undefined implicitly
    • functions can return other functions
  26. Constructors
  27. 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
  28. Constructor functions
    • var Person = function (name) {
    • this .name = name;
    • this .speaks = 'fr' ;
    • this .say = function() {
    • return &quot;Je m'appelle &quot; + this .name;
    • };
    • };
  29. An object created with constructor
    • >>> var julien = new Person( &quot;Julien&quot; );
    • >>> julien.say();
    • &quot;Je m'appelle Julien&quot;
  30. Constructor’s return value
    • var Person = function (){
    • this .first = &quot;Bruce&quot; ;
    • return {last: &quot;Wayne&quot; };
    • };
    • >>> typeof new Person().first
    • &quot;undefined&quot;
    • >>> new Person().last
    • &quot;Wayne&quot;
  31. Constructor’s return value
    • var Person = function (){
    • this .first = &quot;Bruce&quot; ;
    • return &quot;Batman&quot; ;
    • };
    • >>> new Person().first
    • &quot;Bruce&quot;
  32. Naming convention
    • M yConstructor
    • m yFunction
  33. constructor property
    • >>> function Person(){};
    • >>> var jo = new Person();
    • >>> jo. constructor === Person
    • true
  34. constructor property
    • >>> var o = {};
    • >>> o. constructor === Object
    • true
    • >>> [1,2]. constructor === Array
    • true
  35. Built-in constructor functions
    • Object
    • Array
    • Function
    • RegExp
    • Number
    • String
    • Boolean
    • Date
    • Error, SyntaxError, ReferenceError…
  36. var fn = new Function( 'a, b','return a+b'); var fn = function(a, b){ return a + b; } var re = new RegExp( '[a-z]', 'gmi'); var re = /[a-z]/gmi; var a = new Array(); var a = []; var o = new Object(); var o = {}; Not that Use this
  37. Wrapper objects vs. primitive
    • >>> typeof new Number ( 1 )
    • &quot;object&quot;
    • >>> typeof 1
    • &quot;number&quot;
  38. Primitives can act as objects
    • >>> &quot;test&quot; . length
    • 4
    • >>> ( 123.456 ). toFixed ( 2 )
    • &quot;123.46&quot;
  39. Prototype
  40. prototype
    • a property of the function objects
    • >>> var boo = function (){};
    • >>> typeof boo. prototype
    • &quot;object&quot;
  41. Prototypes can be augmented
    • >>> boo. prototype .a = 1 ;
    • >>> boo. prototype .sayAh = function (){};
  42. Prototypes can be overwritten
    • >>> boo. prototype = {a: 1 , b: 2 };
  43. 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;
    • }
    • >>> var dude = new Person( 'dude' );
    • >>> dude.name;
    • &quot;dude&quot;
    • >>> dude.say();
    • &quot;dude&quot;
    How is the prototype used?
    • 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?
  44. Own properties vs. prototype’s
    • >>> dude. hasOwnProperty ( 'name' );
    • true
    • >>> dude. hasOwnProperty ( 'say' );
    • false
  45. isPrototypeOf()
    • >>> Person. prototype . isPrototypeOf (dude);
    • true
    • >>> Object . prototype . isPrototypeOf (dude);
    • true
  46. __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
    • >>> dude. __proto__ . hasOwnProperty ( 'say' )
    • true
    • >>> dude. prototype
    • ??? // Trick question
    • >>> dude. __proto__ . __proto__ . hasOwnProperty ( 'toString' )
    • true
    __proto__
  47. The prototype chain
  48. It’s alive!
    • >>> typeof dude.numlegs
    • &quot;undefined&quot;
    • >>> Person. prototype .numlegs = 2 ;
    • >>> dude.numlegs
    • 2
  49. Inheritance
  50. Inheritance via the prototype
    • >>> var Dad = function (){ this .family = &quot;Stefanov&quot; ;};
    • >>> var Kid = function (){};
    • >>> Kid. prototype = new Dad();
    • >>> var billy = new Kid();
    • >>> billy.family
    • &quot;Stefanov&quot;
  51. Inherit one more time
    • >>> var GrandKid = function (){};
    • >>> GrandKid. prototype = billy;
    • >>> var jill = new GrandKid();
    • >>> jill.family
    • &quot;Stefanov&quot;
  52. Inheritance…
    • >>> jill. hasOwnProperty ( 'family' )
    • false
    • >>> jill. __proto__ . hasOwnProperty ( 'family' )
    • false
    • >>> jill. __proto__ . __proto__ . hasOwnProperty ( 'family' )
    • true
  53. Inheritance…
    • >>> billy.family = 'Idol' ;
    • >>> jill.family;
    • 'Idol'
    • >>> jill. __proto__ . hasOwnProperty ( 'family' );
    • true
    • >>> delete billy.family;
    • >>> jill.family;
    • 'Stefanov'
  54. Side effect…
    • >>> billy. constructor === Kid
    • false
    • >>> billy. constructor === Dad
    • true
  55. Side effect… easy to solve
    • reset after inheritance
    • >>> Kid. prototype . constructor = Kid;
    • >>> GrandKid. prototype . constructor = GrandKid;
  56. isPrototypeOf
    • >>> billy. isPrototypeOf (jill)
    • true
    • >>> Kid. prototype . isPrototypeOf (jill)
    • true
  57. instanceof
    • >>> jill instanceof GrandKid
    • true
    • >>> jill instanceof Kid
    • true
    • >>> jill instanceof Dad
    • true
  58. Classes?
    • There are no classes in JavaScript
    • Objects inherit from objects
    • class ical inheritance is when we think of constructors as if they were classes
  59. Classical inheritance
    • function Parent(){ this .name = 'parent' ;}
    • Parent. prototype .getName = function (){ return this .name; };
    • function Child(){}
    • inherit(Child, Parent);
  60. Option 1
    • function inherit(C, P) {
    • C. prototype = new P();
    • }
  61. Option 2
    • function inherit(C, P) {
    • C. prototype = P. prototype ;
    • }
  62. Option 3
    • function inherit(C, P) {
    • var F = function (){};
    • F. prototype = P. prototype ;
    • C. prototype = new F();
    • }
  63. Option 3 + super
    • function inherit(C, P) {
    • var F = function (){};
    • F. prototype = P. prototype ;
    • C. prototype = new F();
    • C.uber = P. prototype ;
    • }
  64. 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
    • }
  65. 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;
    • }
  66. Inheritance by copying…
    • >>> var parent = {a: 1 };
    • >>> var child = extend(parent);
    • >>> child.a
    • 1
  67. Inheritance by copying…
    • This was a shallow copy
    • you can make a deep copy using recursion
    • mixins / multiple inheritance
  68. Prototypal inheritance
    • as suggested by Douglas Crockford
    • no class-like constructors involved
    • objects inherit from objects
    • via the prototype
  69. Prototypal inheritance
    • function object(o) {
    • function F(){}
    • F. prototype = o;
    • return new F();
    • }
  70. Prototypal inheritance
    • >>> var parent = {a: 1 };
    • >>> var child = object(parent);
    • >>> child.a;
    • 1
    • >>> child. hasOwnProperty (a);
    • false
  71. Scope
  72. No block scope
    • >>> if ( true ) { var inside_block = 1 ;}
    • >>> inside_block
    • 1
  73. Function scope
    • function boo() {
    • var inboo = true ;
    • }
  74. 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
  75. Self-executable functions for one-off tasks
    • ( function (){
    • var a = 1 ;
    • var b = 2 ;
    • alert (a + b);
    • } )()
  76. Closures
  77. Photo credit: NASA
  78.  
  79. Closure example #1
    • function outer(){
    • var local = 1 ;
    • return function (){
    • return local;
    • };
    • }
  80. example #1…
    • >>> var inner = outer()
    • >>> inner()
    • 1
  81. Closure example #2
    • var inner;
    • function outer(){
    • var local = 1 ;
    • inner = function (){
    • return local;
    • };
    • }
  82. example #2…
    • >>> typeof inner
    • &quot;undefined&quot;
    • >>> outer()
    • >>> inner()
    • 1
  83. Closure example #3
    • function makePlus(arg) {
    • var n = function (){
    • return arg;
    • };
    • arg++;
    • return n;
    • }
  84. example #3…
    • >>> var getValue = makePlus( 1234 );
    • >>> getValue()
    • 1235
  85. Closure #4 – in a loop
    • function make() {
    • var i, a = [];
    • for (i = 0 ; i < 3 ; i++) {
    • a[i] = function (){
    • return i;
    • }
    • }
    • return a;
    • }
  86. Closure #4 test - oops
    • >>> var funcs = make();
    • >>> funcs[ 0 ]();
    • 3
    • >>> funcs[ 1 ]();
    • 3
    • >>> funcs[ 2 ]();
    • 3
  87. Closure #4 – corrected
    • function make() {
    • var i, a = [];
    • for (i = 0 ; i < 3 ; i++) {
    • a[i] = ( function (local){
    • return function (){ return local;}
    • })(i)
    • }
    • return a;
    • }
  88. 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
  89. Iterator
    • function setup(x) {
    • var i = 0 ;
    • return function (){
    • return x[i++];
    • };
    • }
  90. Iterator usage
    • >>> var next = setup([ 'a' , 'b' , 'c' ]);
    • >>> next()
    • 'a'
    • >>> next()
    • 'b'
  91. 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);
    • };
    • }
  92. 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)
    • }
  93. Wrapping up…
    • How to tell what’s going on?
    • typeof, instanceof, isPrototypeOf()…
  94. >>> typeof variable
    • typeof is an operator, not a function
    • Not typeof(variable) even if it works
    • Returns a string, one of:
      • &quot;string&quot;, &quot;number&quot;, &quot;boolean&quot;,
      • &quot;undefined&quot;, &quot;object&quot;, &quot;function&quot;
  95. typeof
    • if ( typeof whatever === &quot;undefined&quot;) {
    • // whatever is not defined
    • }
    • if (whatever == undefined) {
    • // hmm, not so sure
    • }
  96. >>> obj instanceof MyConstructor
    • Not instanceof()
    • Returns true | false
    • true for all constructors up the chain
  97. >>> obj. constructor
    • Points to the constructor function used to create this obj
  98. >>> obj. isPrototypeOf (child_obj)
    • Respects the prototype chain
  99. >>> obj. hasOwnProperty ( &quot;prop&quot; )
    • Own properties vs. properties of the prototype
  100. obj. propertyIsEnumerable ( &quot;prop&quot; )
    • 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
  101. Wrapping up…
    • What did we learn today?
  102. Objects
    • JavaScript has a few primitive types, everything else is an object
    • Objects are hashes
    • Arrays are objects
  103. Functions
    • Functions are objects, only invokable
    • call() and apply() methods
    • prototype property
  104. Prototype
    • Functions have a prototype property which is an object
    • Useful with Constructor functions
  105. Constructor
    • A function meant to be called with new
    • Returns an object
  106. Class
    • No such thing in JavaScript
  107. Inheritance
    • Prototypal
    • Class ical
    • … and approximately 101 other ways and variations
  108. Scope
    • Lexical function scope
  109. Closure
    • When a variable leaves its function scope
  110. Thank you!
    • Stoyan Stefanov
    • http://www.phpied.com

+ Stoyan StefanovStoyan Stefanov, 2 years ago

custom

2419 views, 8 favs, 2 embeds more stats

"Advanced JavaScript - prototype, inheritance, clos more

More info about this document

© All Rights Reserved

Go to text version

  • Total Views 2419
    • 2417 on SlideShare
    • 2 from embeds
  • Comments 2
  • Favorites 8
  • Downloads 120
Most viewed embeds
  • 1 views on http://192.168.10.100
  • 1 views on http://ig.gmodules.com

more

All embeds
  • 1 views on http://192.168.10.100
  • 1 views on http://ig.gmodules.com

less

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

Cancel
File a copyright complaint
Having problems? Go to our helpdesk?

Categories