SlideShare a Scribd company logo
1 of 111
Download to read offline
http://www.ļ¬‚ickr.com/photos/tomsly/93947243/ - thomas_sly




A (Re)-Introduction to JavaScript
Simon Willison                             ETech, March 6th, 2005
                                                                   1
                                                                                1
Coming up...

ā€¢ Numbers, Strings and things
ā€¢ Variables and Operators
ā€¢ Control Structures
ā€¢ Objects and Arrays
ā€¢ Functions
ā€¢ Object constructors and inheritance
ā€¢ Inner functions and closures
ā€¢ Memory Leaks... and more
2

                                        2
Book recommendation

    ā€¢ JavaScript: The
      Definitive Guide
      ā€“ by David Flanagan
    ā€¢ Comprehensive
      overview of the
      language in the first
      20 chapters
    ā€¢ New edition out later
      this year
3

                              3
More book recommendations

ā€¢ For practical applications of this stuff:




4

                                              4
You will need...

ā€¢ Firefox
    ā€“ Any web browser can run JavaScript, but
      Firefox has the best tools for developers
ā€¢ Jesse Ruderman's 'shell' tool
    ā€“ http://www.squarefree.com/shell/
ā€¢ A text editor may come in handy too



5

                                                  5
In the words of its creator

        JavaScript was a rushed little hack for
    Netscape 2 that was then frozen prematurely
        during the browser wars, and evolved
    significantly only once by ECMA. So its early
        flaws were never fixed, and worse, no
       virtuous cycle of fine-grained community
    feedback in the form of standard library code
    construction, and revision of the foundational
      parts of the language to better support the
     standard library and its common use-cases,
                     ever occurred.
6
                       http://weblogs.mozillazine.org/roadmap/archives/2006/02/js_and_python_news.html
                                                                                                    6
http://www.ļ¬‚ickr.com/photos/kingcoyote/93491484/ - King Coyote




The History of JavaScript
       (in 30 seconds)




                                                                7
                                                                             7
JavaScript was...



       Invented by Brendan Eich in 1995 for
    Netscape; originally called LiveScript, current
    name being an ill-fated marketing decision to
       tie in with Sun's newly released Java;
     adapted by Microsoft as JScript for IE 3 in
    1996; standardised as ECMAScript in 1997;
      sort-of included in Flash as ActionScript;
     updated to ECMAScript 3rd edition in 1998

8

                                                      8
Not quite general purpose

ā€¢ No direct concept of input or output
ā€¢ Runs within a host environment
    ā€“ Web browser
    ā€“ Adobe Acrobat
    ā€“ Photoshop
    ā€“ Windows Scripting Host
    ā€“ Yahoo! Widget Engine
    ā€“ and more...
9

                                         9
http://www.ļ¬‚ickr.com/photos/olivepress/11223013/ - Brian Sawyer




Syntax


                                                                10
Reserved words

                 break else new var
              case finally return void
               catch for switch while
            continue function this with
                  default if throw
                    delete in try
                do instanceof typeof

                abstract enum int short
           boolean export interface static
                byte extends long super
            char final native synchronized
              class float package throws
             const goto private transient
       debugger implements protected volatile
                  double import public

11

                                                11
Style recommendations

ā€¢ Avoid semi-colon insertion like the plague


     ;;;                        friends
ā€¢ Declare variables religiously with 'var'
ā€¢ Global variables are evil. Avoid them if you
  can.
ā€¢ Indent consistently

12

                                                 12
http://www.ļ¬‚ickr.com/photos/kvitsh/64919318/ - K'vitsh / Heather Hutchinson




Types

                                                             13
                                                                          13
JavaScript types

ā€¢ Numbers
ā€¢ Strings
ā€¢ Booleans
ā€¢ Functions
ā€¢ Objects




14

                   14
JavaScript types (improved)

ā€¢    Number
ā€¢    String
ā€¢    Boolean
ā€¢    Object
     ā€“ Function
     ā€“ Array
     ā€“ Date
     ā€“ RegExp
ā€¢ Null
ā€¢ Undefined
15

                              15
http://www.ļ¬‚ickr.com/photos/51035555243@N01/72778694/ - Thomas Hawk




Numbers

                                                       16
                                                                  16
Numbers

ā€¢ quot;double-precision 64-bit format IEEE 754
  valuesquot;
ā€¢ No such thing as an integer
     0.1 + 0.2 = 0.30000000000000004
     3 + 5.3
     28 % 6 etc...
ā€¢ Math namespace for advanced operations


17

                                             17
Math stuff

ā€¢ Math.PI, Math.E, Math.LN10,
  Math.LN2, Math.LOG10E,
  Math.SQRT1_2, Math.SQRT2
ā€¢ Math.abs(x), Math.acos(x),
  Math.asin(x), Math.atan(x),
  Math.atan2(y, x), Math.ceil(x),
  Math.cos(x), Math.exp(x),
  Math.floor(x), Math.log(x),
  Math.max(x, ..), Math.min(x, ..),
  Math.pow(x, y), Math.random(),
  Math.round(x), Math.sin(x),
  Math.sqrt(x), Math.tan(x)
18

                                      18
parseInt (and parseFloat)

ā€¢ parseInt converts a string to a number
       > parseInt(quot;123quot;);
       123
       > parseInt(quot;010quot;);      Always specify the base
       8
ā€¢ !?
       > parseInt(quot;010quot;, 10);
       10
       > parseInt(quot;11quot;, 2)
       3
19

                                                         19
NaN and Infinity

     > parseInt(quot;helloquot;, 10)
     NaN
ā€¢ NaN is toxic
     > NaN + 5
     NaN
     > isNaN(NaN)
     true
ā€¢ Special values for Infinity and -Infinity:
     >1/0                     > -1 / 0
     Infinity                 -Infinity
20

                                               20
http://www.ļ¬‚ickr.com/photos/solarider/53494967/ - solarider




Strings

                                                 21
                                                              21
Strings

ā€¢ Sequences of characters
ā€¢ Sequences of unicode characters (16 bit)
     quot;u0020quot;
ā€¢ A character is a string of length 1
     > quot;helloquot;.length
     5
ā€¢ Strings are objects!

22

                                             22
String methods

     > quot;helloquot;.charAt(0)
     h
     > quot;hello, worldquot;.replace(quot;helloquot;,
     quot;goodbyequot;)
     goodbye, world
     > quot;helloquot;.toUpperCase()
     HELLO


23

                                         23
More string methods

         s.charAt(pos) s.charCodeAt(pos)
                   s.concat(s1, ..)
                s.indexOf(s1, start)
           s.lastIndexOf(s1, startPos)
         s.localeCompare(s1) s.match(re)
            s.replace(search, replace)
        s.search(re) s.slice(start, end)
             s.split(separator, limit)
               s.substring(start, end)
     s.toLowerCase() s.toLocaleLowerCase()
     s.toUpperCase() s.toLocaleUpperCase()
24

                                             24
Null and undefined

ā€¢ null = deliberately no value
ā€¢ undefined = no value assigned yet
     ā€“ Variables declared but not initialised
     ā€“ Object/array members that don't exist
     ā€“ (More on this later)




25

                                                25
Booleans

ā€¢ Boolean type: true or false
ā€¢ Everything else is quot;truthyquot; or quot;falsyquot;
ā€¢ 0, quot;quot;, NaN, null, undefined are falsy
ā€¢ Everything else is truthy
ā€¢ Boolean operations: &&, || and !
ā€¢ Convert any value to it's boolean equivalent
  by applying not twice:
                             > !!234
     > !!quot;quot;
                             true
     false
26

                                                 26
http://www.ļ¬‚ickr.com/photos/antmoose/71277315/ - antmoose / Anthony M.




Variables and operators

                                                                  27
                                                                              27
Variable declaration

ā€¢ New variables in JavaScript are declared
  using the var keyword:
       var a;
       var name = quot;simonquot;;
ā€¢ If you declare a variable without assigning it
  to anything, its value is undefined.
     If you forget the var, you get a global
     variable. Never, ever do this - not even if
     you mean it.
28

                                                   28
Operators

     Numeric operators: +, -, *, / and %
ā€¢ Compound assignment operators:
       +=, -=, *=, /=, %=
ā€¢ Increment and decrement:
       a++, ++a, b--, --b
ā€¢ String concatenation:
       > quot;helloquot; + quot; worldquot;
       hello world
29

                                           29
Type coercion

     > quot;3quot; + 4 + 5
     345
     > 3 + 4 + quot;5quot;
     75


ā€¢ Adding an empty string to something else
  converts it to a string.


30

                                             30
Comparison

ā€¢ >, <, >=, <= work for numbers and strings
ā€¢ Equality tests use == and != ... sort of
     > quot;dogquot; == quot;dogquot;
     true
     > 1 == true
     true
ā€¢ === and !== avoid type coercion
     > 1 === true
     false
     > true === true
     true
31

                                              31
The typeof operator

     typeof v
                number      'number'
                string      'string'
                boolean     'boolean'
                function    'function'
                object      'object'
                array       'object'
                null        'object'
                undefined   'undefined'
32

                                          32
http://www.ļ¬‚ickr.com/photos/setre/8825214/ - setre




Control structures

                                                33
                                                             33
if statements

     var name = quot;kittensquot;;
     if (name == quot;puppiesquot;) {
       name += quot;!quot;;
     } else if (name == quot;kittensquot;) {
       name += quot;!!quot;;
     } else {
       name = quot;!quot; + name;
     }
     name == quot;kittens!!quot;
34

                                       34
while and do-while

     while (true) {
         // an infinite loop!
     }


     do {
         var input = get_input();
     } while (inputIsNotValid(input))

35

                                        35
for loops

     for (var i = 0; i < 5; i++) {
       // Will execute 5 times
     }




36

                                     36
switch statement

ā€¢ Multiple branches depending on a number or
  string
     switch(action) {
         case 'draw':
             drawit();
             break;
         case 'eat':
             eatit();
             break;
         default:
             donothing();
     }
37

                                               37
fall through

     switch(a) {
         case 1: // fallthrough
         case 2:
             eatit();
             break;
         default:
             donothing();
     }
ā€¢ Deliberate labelling of fall through is good
  practise

38

                                                 38
Switch expressions

ā€¢ Expressions are allowed
ā€¢ Comparisons take place using ===
     switch(1 + 3):
         case 2 + 2:
             yay();
             break;
         default:
             neverhappens();
     }
39

                                     39
Short-circuit logic

ā€¢ The && and || operators use short-circuit
  logic: they will execute their second operand
  dependant on the first.
ā€¢ This is useful for checking for null objects
  before accessing their attributes:
     var name = o && o.getName();
ā€¢ Or for setting default values:
     var name = otherName || quot;defaultquot;;

40

                                                  40
The tertiary operator

ā€¢ One-line conditional statements
     var ok = (age > 18) ? quot;yesquot; : quot;noquot;;
ā€¢ Easy to abuse; use with caution




41

                                           41
Exceptions

     try {
       // Statements in which
       // exceptions might be thrown
     } catch(error) {
       // Statements that execute
       // in the event of an exception
     } finally {
       // Statements that execute
       // afterward either way
     }

     throw new Error(quot;An error!quot;);
     throw quot;Another error!quot;;

42

                                         42
http://www.ļ¬‚ickr.com/photos/spengler/51617271/ - Andreas D.




Objects

                                                 43
                                                             43
Objects

ā€¢ Simple name-value pairs, as seen in:
     ā€“ Dictionaries in Python
     ā€“ Hashes in Perl and Ruby
     ā€“ Hash tables in C and C++
     ā€“ HashMaps in Java
     ā€“ Associative arrays in PHP
ā€¢ Very common, versatile data structure
ā€¢ Name part is a string; value can be anything
44

                                                 44
Basic object creation

     var obj = new Object();
ā€¢ Or:
     var obj = {};
ā€¢ These are semantically equivalent; the
  second is called object literal syntax and is
  more convenient.



45

                                                  45
Property access

     obj.name = quot;Simonquot;
     var name = obj.name;
ā€¢ Or...
     obj[quot;namequot;] = quot;Simonquot;;
     var name = obj[quot;namequot;];
ā€¢ Semantically equivalent; the second uses
  strings so can be decided at run-time (and
  can be used for reserved words)
46

                                               46
Object literal syntax

 var obj = {
   name: quot;Carrotquot;,
   quot;forquot;: quot;Maxquot;,
   details: {
     color: quot;orangequot;,
     size: 12
   }
 }

 > obj.details.color    > obj[quot;detailsquot;][quot;sizequot;]
 orange                 12

47

                                              47
for (var attr in obj)

ā€¢ You can iterate over the keys of an object:
     var obj = { 'name': 'Simon', 'age': 25};
     for (var attr in obj) {
         print (attr + ' = ' + obj[attr]);
     }

ā€¢ Don't attempt this with arrays (coming up
  next). There are safer ways of iterating over
  them.

48

                                                  48
http://www.ļ¬‚ickr.com/photos/adrian_s/28567268/ - wafļ¬‚er / Adrian Sampson




Arrays

                                                           49
                                                                       49
Arrays

ā€¢ A special type of object: Keys are whole
  numbers, not strings.
ā€¢ Use [] syntax, just like objects
     > var a = new Array();
     > a[0] = quot;dogquot;;
     > a[1] = quot;catquot;;
     > a[2] = quot;henquot;;
     > a.length
     3
50

                                             50
Array literals

ā€¢ More convenient notation:
     > var a = [quot;dogquot;, quot;catquot;, quot;henquot;];
     > a.length
     3




51

                                        51
array.length

     > var a = [quot;dogquot;, quot;catquot;, quot;henquot;];
     > a[100] = quot;foxquot;;
     > a.length
     101
     typeof a[90] == 'undefined'
ā€¢ array.length is always one more than the
  highest index
ā€¢ The safest way to append new items is:
     a[a.length] = item;
52

                                             52
Array iteration

     for (var i = 0; i < a.length; i++) {
         // Do something with a[i]
     }



ā€¢ Improve this by caching a.length at start:


     for (var i = 0, j = a.length; i < j; i++) {
         // Do something with a[i]
     }
53

                                                   53
Even better iteration

     for (var i = 0, item; item = a[i]; i++) {
         // Do something with item
     }

ā€¢ This trick only works with arrays that are
  known not to contain falsy values. The
  following array will break with the above
  idiom:
     var a = [10, quot;dogquot;, false, quot;elephantquot;];
ā€¢ (Yes, you can have mixed content in arrays)
54

                                                 54
Array methods

          a.toString(), a.toLocaleString(),
     a.concat(item, ..), a.join(sep), a.pop(),
     a.push(item, ..), a.reverse(), a.shift(),
         a.slice(start, end), a.sort(cmpfn),
        a.splice(start, delcount, [item]..),
                 a.unshift([item]..)




55

                                                 55
3.2




                                       2.4




                                       1.6




                                       0.8




.8   -4   -3.2   -2.4   -1.6    -0.8    0     0.8   1.6   2.4   3.2        4    4.8




                                       -0.8




                               Functions
                                       -1.6




                                       -2.4




                                       -3.2
                                                                      56
                                                                               56
Functions

ā€¢ Don't get much simpler than this:
     function add(x, y) {
         var total = x + y;
         return total;
     }
ā€¢ If nothing is explicitly returned, return value is
  undefined


57

                                                       57
Arguments

ā€¢ Parameters: quot;They're more like... guidelinesquot;
ā€¢ Missing parameters are treated as undefined:
     > add()
     Nan // addition on undefined
ā€¢ You can pass in more arguments than
  expected:
     > add(2, 3, 4)
     5 // added the first two; 4 was ignored

ā€¢ How is this behaviour useful?
58

                                                  58
arguments

ā€¢ The arguments special variable provides
  access to arguments as an array-like object
     function add() {
         var sum = 0;
         for (var i = 0, j = arguments.length;
             i < j; i++) {
             sum += arguments[i];
         }
         return sum;
     }

     > add(2, 3, 4, 5)
     14
59

                                                 59
avg()

ā€¢ More useful: an averaging function:
     function avg() {
         var sum = 0;
         for (var i = 0, j = arguments.length;
             i < j; i++) {
             sum += arguments[i];
         }
         return sum / arguments.length;
     }
60

                                                 60
Averaging an array?

ā€¢ Our fancy multi-argument function isn't much
  good if our data is already in an array. Do we
  have to rewrite it?
     function avgArray(arr) {
         var sum = 0;
         for (var i = 0, j = arr.length;
             i < j; i++) {
             sum += arguments[i];
         }
         return sum / arr.length;
     }

61

                                                   61
Using avg() with an array

ā€¢ That's not necessary:
     > avg.apply(null, [2, 3, 4, 5])
     3.5
ā€¢ Functions are objects with methods too!
ā€¢ The apply method takes an array of
  argments as the second argument...
ā€¢ We'll find out about the first argument a little
  later

62

                                                     62
Anonymous functions

ā€¢ The following is semantically equivalent to
  our earlier avg() function:
     var avg = function() {
         var sum = 0;
         for (var i = 0, j = arguments.length;
             i < j; i++) {
             sum += arguments[i];
         }
         return sum / arguments.length;
     }

63

                                                 63
The block scope trick

ā€¢ Block scope is a feature of C where every
  set of braces defines a new scope. It can be
  simulated in JavaScript:
     var a = 1;
     var b = 2;
     (function() {
         var b = 3;
         a += b;
     })();
     >a
     4
     >b
     2
64

                                                 64
Recursive functions

     function countChars(elm) {
         if (elm.nodeType == 3) { // TEXT_NODE
             return elm.nodeValue.length;
         }
         var count = 0;
         for (var i = 0, child;
             child = elm.childNodes[i]; i++) {
             count += countChars(child);
         }
         return count;
     }
65

                                                 65
arguments.callee

ā€¢ arguments.callee is the current function:
     var charsInBody = (function(elm) {
         if (elm.nodeType == 3) { // TEXT_NODE
             return elm.nodeValue.length;
         }
         var count = 0;
         for (var i = 0, child;
             child = elm.childNodes[i]; i++) {
             count += arguments.callee(child);
         }
         return count;
     })(document.body);
66

                                                 66
arguments.callee to save state

ā€¢ This function remembers how many times it
  has been called:
     function counter() {
         if (!arguments.callee.count) {
             arguments.callee.count = 0;
         }
         return arguments.callee.count++;
     }
     > counter()
     0
     > counter()
     1
67

                                              67
http://www.ļ¬‚ickr.com/photos/45339031@N00/100472474/ - piccadillywilson / Matt




Constructors

                                                                  68
                                                                              68
Functions and objects

     function makePerson(first, last) {
         return {
             first: first,
             last: last
         }
     }
     function personFullName(person) {
         return person.first + ' ' +
             person.last;
     }
     function personFullNameReversed(person) {
         return person.last + ', ' +
             person.first
     }
69

                                                 69
Functions and objects (II)

     > s = makePerson(quot;Simonquot;,
     quot;Willisonquot;);
     > personFullName(s)
     Simon Willison
     > personFullNameReversed(s)
     Willison, Simon
ā€¢ Surely we can attach functions to the objects
  themselves?
70

                                                  70
Methods, first try

     function makePerson(first, last) {
       return {
         first: first,
         last: last,
         fullName: function() {
            return this.first + ' ' +
              this.last;
         },
         fullNameReversed: function() {
            return this.last + ', ' +
              this.first;
         }
       }
     }
71

                                          71
Using methods

     > s = makePerson(quot;Simonquot;,
     quot;Willisonquot;)
     > s.fullName()
     Simon Willison
     > s.fullNameReversed()
     Willison, Simon



72

                                 72
dot notation is required

     > s = makePerson(quot;Simonquot;,
     quot;Willisonquot;)
     > var fullName = s.fullName;
     > fullName()
     undefined undefined
ā€¢ If you call a function without using dot
  notation, 'this' is set to the global object. In
  the browser, this is the same as 'window'.

73

                                                     73
Constructors

     function Person(first, last) {
       this.first = first;
       this.last = last;
       this.fullName = function() {
         return this.first + ' ' +
           this.last;
       }
       this.fullNameReversed = function() {
         return this.last + ', ' +
           this.first;
       }
     }
     var s = new Person(quot;Simonquot;, quot;Willisonquot;);

74

                                                74
new

ā€¢ 'new' creates a new empty object and calls
  the specified function with 'this' set to that
  object.
ā€¢ These constructor functions should be
  Capitalised, as a reminder that they are
  designed to be called using 'new'
ā€¢ This is key to understanding JavaScript's
  object model


75

                                                   75
Sharing methods

     function personFullName() {
         return this.first + ' ' +
             this.last;
     }
     function personFullNameReversed() {
         return this.last + ', ' +
             this.first;
     }
     function Person(first, last) {
         this.first = first;
         this.last = last;
         this.fullName = personFullName;
         this.fullNameReversed =
             personFullNameReversed;
     }
76

                                           76
Person.prototype

     function Person(first, last) {
         this.first = first;
         this.last = last;
     }
     Person.prototype.fullName =
       function() {
         return this.first + ' ' +
           this.last;
     }
     Person.prototype.fullNameReversed =
       function() {
         return this.last + ', ' +
           this.first;
     }
77

                                           77
instanceof

ā€¢ The instanceof operator can be used to test
  the type of an object, based on its
  constructor (and prototype hierarchy,
  explained in the next section).
     var a = [1, 2, 3];
     a instanceof Array
     true
     a instanceof Object
     true
     a instanceof String
     false
78

                                                78
http://www.ļ¬‚ickr.com/photos/bingolittle/5803243/ - Bingo Little




Inheritance

                                                      79
                                                                    79
Adding to an existing set of objects

     > s = new Person(quot;Simonquot;,
     quot;Willisonquot;);
     > s.firstNameCaps();
     TypeError on line 1:
     s.firstNameCaps is not a function
     > Person.prototype.firstNameCaps =
     function() {
         return this.first.toUpperCase()
     }
     > s.firstNameCaps()
     SIMON
80

                                           80
Extending core objects

     > var s = quot;Simonquot;;
     > s.reversed()
     TypeError: s.reversed is not a function
     > String.prototype.reversed = function() {
        var r = '';
        for (var i = this.length - 1; i >= 0; i--){
           r += this[i];
        }
        return r;
     }
     > s.reversed()
     nomiS
     > quot;This can now be reversedquot;.reversed()
     desrever eb won nac sihT
81

                                                      81
Object.prototype

ā€¢ All prototype chains terminate at
  Object.prototype
ā€¢ Its methods include toString(), which we can
  over-ride:
     > var s = new Person(quot;Simonquot;, quot;Willisonquot;);
     >s
     [object Object]
     > Person.prototype.toString = function() {
        return '<Person: ' + this.fullName() + '>';
     }
     >s
     <Person: Simon Willison>
82

                                                      82
Perils of modifying Object.prototype

ā€¢ Remember for (var attr in obj)?
ā€¢ It will include stuff that's been newly added to
  Object.prototype
ā€¢ This stupid behaviour is sadly baked in to the
  language
ā€¢ Some libraries (Prototype is a prime
  offender) do it anyway


83

                                                     83
So what about inheritance?

ā€¢ Problem: JavaScript is a prototype-based
  language, but it pretends to be a class-based
  language
ā€¢ As a result, it doesn't do either very well
ā€¢ Inheritance doesn't quite behave how you
  would expect




84

                                                  84
Here's a special kind of person
     function Geek() {
       Person.apply(this, arguments);
       this.geekLevel = 5;
     }
     Geek.prototype = new Person();
     Geek.prototype.setLevel = function(lvl) {
       this.geekLevel = lvl;
     }
     Geek.prototype.getLevel = function() {
       return this.geekLevel;
     }
     > s = new Geek(quot;Simonquot;, quot;Willisonquot;)
     > s.fullName()
     Simon Willison
     > s.getLevel()
     5
85

                                                 85
new Person()?

ā€¢ We're using an instance of the Person object
  as our prototype
ā€¢ We have to do this, because we need to be
  able to modify our prototype to add new
  methods that are only available to Geek
  instances
ā€¢ This is counter-intuitive and, well, a bit dumb



86

                                                    86
Solutions?

ā€¢ Design classes with inheritance in mind -
  don't do anything important in the constructor
  (that might break if you create an empty
  instance for use as a prototype)
ā€¢ Use one of the many workarounds
     ā€“ Prototype's Class.create()
     ā€“ The stuff you get by searching for quot;javascript
       inheritancequot; on the Web


87

                                                        87
http://en.wikipedia.org/wiki/Image:Torres_Petronas_Mayo_2004.jpg Ɓngel Riesgo Martƭnez




Higher order functions

                                                                              88
                                                                                          88
Functions are first-class objects

ā€¢ In English...
     ā€“ A function is just another object
     ā€“ You can store it in a variable
     ā€“ You can pass it to another function
     ā€“ You can return it from a function




89

                                             89
VAT
VAT is England's national sales tax - 17.5%

     var prices = [10, 8, 9.50];
     var pricesVat = [];
     for (var i = 0; i < prices.length; i++)
     {
         pricesVat[i] = prices[i] * 1.175;
     }




90

                                               90
arrayMap
 function arrayMap(array, func) {
   var result = [];
   for (var i = 0; i < array.length; i++) {
     result[i] = func(array[i]);
   }
   return result;
 }

 function calcVat(price) {
   return price * 1.175;
 }

 var prices = [10, 8, 9.50];
 pricesVat = arrayMap(prices, calcVat);

91

                                              91
salesTaxFactory
What if we want to calculate sales tax at 4%?

     function salesTaxFactory(percent) {
       function func(price) {
         return price + (percent / 100) * price;
       }
       return func;
     }

     calcVat = salesTaxFactory(17.5);
     calc4 = salesTaxFactory(4);

     pricesVat = arrayMap(prices, calcVat);
     prices4 = arrayMay(prices, calc4);

92

                                                   92
An operation factory
     function makeOp(op, y) {
       switch (op) {
         case '+':
           return function(x) { return   x + y };
         case '-':
           return function(x) { return   x - y };
         case '/':
           return function(x) { return   x / y };
         case '*':
           return function(x) { return   x * y };
         default:
           return function(x) { return   x };
       }
     }
     var third = makeOp('/', 3);
     var dbl = makeOp('*', 2);
     print(third(24));
     print(dbl(5));
93

                                                    93
Closures

ā€¢ The previous code was an example of
  closures in action
ā€¢ A closure is a function that has captured the
  scope in which it was defined
ā€¢ Actually, functions in JavaScript have a
  scope chain (similar to the prototype chain)




94

                                                  94
What does this do?
     function openLinksInNewWindows() {
         for (var i = 0; i < document.links.length; i++) {
             document.links[i].onclick = function() {
                 window.open(document.links[i].href);
                 return false;
             }
         }
     }

ā€¢ The onclick function is a closure which refers back
  to the original scope; it does NOT retain a copy of
  the i variable at the time the function was created.
  By the time the onclick function is executed, i will
  be the last value assigned by the loop.
95

                                                             95
http://www.ļ¬‚ickr.com/photos/iboy_daniel/90450551/ - iboy_daniel / doug wilson




Singleton

                                                                96
                                                                             96
Namespace pollution

ā€¢ JavaScript shares a single global
  namespace
ā€¢ Itā€™s easy to clobber other peopleā€™s functions
  and variables
ā€¢ Itā€™s easy for other people to clobber yours
ā€¢ The less code affecting the global
  namespace the better


97

                                                  97
The singleton pattern
     var simon = (function() {
       var myVar = 5; // Private variable
       function init(x) {
         // ... can access myVar and doPrivate
       }
       function doPrivate(x) {
         // ... invisible to the outside world
       }
       function doSomething(x, y) {
         // ... can access myVar and doPrivate
       }
       return {
         'init': init, 'doSomething': doSomething
       }
     })();

     simon.init(x);


98

                                                    98
Singleton benefits

ā€¢ Singleton lets you wrap up a complex
  application with dozens of functions up in a
  single, private namespace - a closure
ā€¢ This lets you expose only the functions that
  make up your application's external interface




99

                                                  99
http://www.ļ¬‚ickr.com/photos/lunchtimemama/97685471/ - lunchtimemama / Scott




Memory leaks

                                                                100
                                                                           100
Internet Explorer sucks

ā€¢ To understand memory leaks, you have to
  understand a bit about garbage collection
ā€¢ Stuff gets freed up automatically when it is
  no longer in use (both JavaScript objects and
  host objects, such as DOM nodes)
ā€¢ IE uses different garbage collectors for JS
  and for the DOM, and can't handle circular
  references between them


101

                                                101
This leaks

      function leak() {
          var div = document.getElementById('d');
          div.obj = {

              'leak': div
          }
      }

ā€¢ Call it enough times and IE will crash




102

                                                    102
This also leaks

      function sneakyLeak() {
          var div = document.getElementById('d');
          div.onclick = function() {

              alert(quot;hi!quot;);
          }
      }

ā€¢ Why? Spot the closure!




103

                                                    103
Difficulties

ā€¢ These things can be very hard to detect -
  especially in large, complex applications
  where a cycle might occur over many nodes
  and JavaScript objects
ā€¢ One solution:
      function noLeak() {
        var div = document.getElementById('d');
        div.onclick = function() {
          alert(quot;hi!quot;);
        }
        div = null;
      }
104

                                                  104
More solutions

ā€¢ Most popular JavaScript libraries have
  systems for attaching and detaching events
ā€¢ Many of these can automatically free event
  references when the page is unloaded
ā€¢ Use these, but always be aware of the
  problem




105

                                               105
http://www.ļ¬‚ickr.com/photos/javic/100567276/ - javic




Performance

                                            106
                                                        106
Performance tips

ā€¢ De-reference complex lookups
      var s = document.getElementById('d').style;
      s.width = '100%';
      s.color = 'red';
      // ...
      s.display = 'block';

ā€¢ ... especially inside loops
      var lookup = foo.bar.bav;
      for (var i = 0; i < 1000; i++) {
          lookup.counter += someCalc();
      }
107

                                                    107
http://www.ļ¬‚ickr.com/photos/klara/94704029/ - klara(!) / klara




Libraries

                                                    108
                                                                108
Suggested libraries



             ĀÆĀÆ
          dojotoolkit.org
                                developer.yahoo.net/yui/




                            prototype.conio.net

      mochikit.com


                              script.aculo.us
109

                                                           109
Tell Alex I told you this...
ā€¢ Everything in JavaScript is an Object. Even
  functions
ā€¢ Every object is always mutable
ā€¢ The dot operator is equivalent to de-referencing by
  hash (e.g., foo.bar === foo[quot;barquot;])
ā€¢ The new keyword creates an object that class
  constructors run inside of, thereby imprinting them
ā€¢ Functions are always closures (combine w/ previous
  rule to create OOP)
ā€¢ The this keyword is relative to the execution context,
  not the declaration context
ā€¢ The prototype property is mutable
110

                                                           110
http://www.ļ¬‚ickr.com/photos/nataliedowne/14517351/ - NatBat / Natalie Downe




Thank you!
                                                              111
                                                                          111

More Related Content

What's hot

JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript BasicsMats Bryntse
Ā 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran Khoa
Ā 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
Ā 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
Ā 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScriptT11 Sessions
Ā 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
Ā 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
Ā 
Javascript basics
Javascript basicsJavascript basics
Javascript basicsshreesenthil
Ā 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
Ā 
Javascript
JavascriptJavascript
JavascriptAditya Gaur
Ā 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...Edureka!
Ā 
Basic Javascript
Basic JavascriptBasic Javascript
Basic JavascriptBunlong Van
Ā 
Javascript
JavascriptJavascript
Javascripttheacadian
Ā 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
Ā 
Javascript
JavascriptJavascript
Javascriptmussawir20
Ā 
Javascript 101
Javascript 101Javascript 101
Javascript 101Shlomi Komemi
Ā 

What's hot (20)

JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Ā 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
Ā 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Ā 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Ā 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
Ā 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Ā 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Ā 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
Ā 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Ā 
Javascript
JavascriptJavascript
Javascript
Ā 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
Ā 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
Ā 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
Ā 
JavaScript Basics and Trends
JavaScript Basics and TrendsJavaScript Basics and Trends
JavaScript Basics and Trends
Ā 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
Ā 
Javascript
JavascriptJavascript
Javascript
Ā 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Ā 
Javascript
JavascriptJavascript
Javascript
Ā 
Javascript 101
Javascript 101Javascript 101
Javascript 101
Ā 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
Ā 

Similar to A Re-Introduction to JavaScript

javascript teach
javascript teachjavascript teach
javascript teachguest3732fa
Ā 
JSBootcamp_White
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_Whiteguest3732fa
Ā 
Ruby on Rails in UbiSunrise
Ruby on Rails in UbiSunriseRuby on Rails in UbiSunrise
Ruby on Rails in UbiSunriseWisely chen
Ā 
JavaScript Beginner Tutorial | WeiYuan
JavaScript Beginner Tutorial | WeiYuanJavaScript Beginner Tutorial | WeiYuan
JavaScript Beginner Tutorial | WeiYuanWei-Yuan Chang
Ā 
Reverse Engineering Malicious Javascript
Reverse Engineering Malicious JavascriptReverse Engineering Malicious Javascript
Reverse Engineering Malicious JavascriptYusuf Motiwala
Ā 
Javascript The Good Parts
Javascript The Good PartsJavascript The Good Parts
Javascript The Good PartsFederico Galassi
Ā 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Coursepeter_marklund
Ā 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Developmentwolframkriesing
Ā 
Os Wilhelm
Os WilhelmOs Wilhelm
Os Wilhelmoscon2007
Ā 
Rubinius - A Tool of the Future
Rubinius - A Tool of the FutureRubinius - A Tool of the Future
Rubinius - A Tool of the Futureevanphx
Ā 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2rubyMarc Chung
Ā 
Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
Jazz up your JavaScript: Unobtrusive scripting with JavaScript librariesJazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
Jazz up your JavaScript: Unobtrusive scripting with JavaScript librariesSimon Willison
Ā 
Ruby Under The Hood
Ruby Under The HoodRuby Under The Hood
Ruby Under The Hoodcraig lehmann
Ā 
DLW Europe - JavaScript Tooling
DLW Europe - JavaScript ToolingDLW Europe - JavaScript Tooling
DLW Europe - JavaScript ToolingFabian Jakobs
Ā 
Vidoop CouchDB Talk
Vidoop CouchDB TalkVidoop CouchDB Talk
Vidoop CouchDB TalkChris Anderson
Ā 
Intro to J Ruby
Intro to J RubyIntro to J Ruby
Intro to J RubyFrederic Jean
Ā 
how to hack with pack and unpack
how to hack with pack and unpackhow to hack with pack and unpack
how to hack with pack and unpackDavid Lowe
Ā 

Similar to A Re-Introduction to JavaScript (20)

javascript teach
javascript teachjavascript teach
javascript teach
Ā 
JSBootcamp_White
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_White
Ā 
Ruby on Rails in UbiSunrise
Ruby on Rails in UbiSunriseRuby on Rails in UbiSunrise
Ruby on Rails in UbiSunrise
Ā 
JavaScript Beginner Tutorial | WeiYuan
JavaScript Beginner Tutorial | WeiYuanJavaScript Beginner Tutorial | WeiYuan
JavaScript Beginner Tutorial | WeiYuan
Ā 
Reverse Engineering Malicious Javascript
Reverse Engineering Malicious JavascriptReverse Engineering Malicious Javascript
Reverse Engineering Malicious Javascript
Ā 
Scala Sjug 09
Scala Sjug 09Scala Sjug 09
Scala Sjug 09
Ā 
Javascript The Good Parts
Javascript The Good PartsJavascript The Good Parts
Javascript The Good Parts
Ā 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ā 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
Ā 
Jvm Language Summit Rose 20081016
Jvm Language Summit Rose 20081016Jvm Language Summit Rose 20081016
Jvm Language Summit Rose 20081016
Ā 
Os Wilhelm
Os WilhelmOs Wilhelm
Os Wilhelm
Ā 
Rubinius - A Tool of the Future
Rubinius - A Tool of the FutureRubinius - A Tool of the Future
Rubinius - A Tool of the Future
Ā 
Practical Groovy DSL
Practical Groovy DSLPractical Groovy DSL
Practical Groovy DSL
Ā 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
Ā 
Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
Jazz up your JavaScript: Unobtrusive scripting with JavaScript librariesJazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
Ā 
Ruby Under The Hood
Ruby Under The HoodRuby Under The Hood
Ruby Under The Hood
Ā 
DLW Europe - JavaScript Tooling
DLW Europe - JavaScript ToolingDLW Europe - JavaScript Tooling
DLW Europe - JavaScript Tooling
Ā 
Vidoop CouchDB Talk
Vidoop CouchDB TalkVidoop CouchDB Talk
Vidoop CouchDB Talk
Ā 
Intro to J Ruby
Intro to J RubyIntro to J Ruby
Intro to J Ruby
Ā 
how to hack with pack and unpack
how to hack with pack and unpackhow to hack with pack and unpack
how to hack with pack and unpack
Ā 

More from Simon Willison

How Lanyrd does Geo
How Lanyrd does GeoHow Lanyrd does Geo
How Lanyrd does GeoSimon Willison
Ā 
Cheap tricks for startups
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startupsSimon Willison
Ā 
The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)Simon Willison
Ā 
How we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphHow we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphSimon Willison
Ā 
Web Services for Fun and Profit
Web Services for Fun and ProfitWeb Services for Fun and Profit
Web Services for Fun and ProfitSimon Willison
Ā 
Tricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationTricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationSimon Willison
Ā 
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricAdvanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricSimon Willison
Ā 
How Lanyrd uses Twitter
How Lanyrd uses TwitterHow Lanyrd uses Twitter
How Lanyrd uses TwitterSimon Willison
Ā 
Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approvalSimon Willison
Ā 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesSimon Willison
Ā 
Building crowdsourcing applications
Building crowdsourcing applicationsBuilding crowdsourcing applications
Building crowdsourcing applicationsSimon Willison
Ā 
Evented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesEvented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesSimon Willison
Ā 
Cowboy development with Django
Cowboy development with DjangoCowboy development with Django
Cowboy development with DjangoSimon Willison
Ā 
Crowdsourcing with Django
Crowdsourcing with DjangoCrowdsourcing with Django
Crowdsourcing with DjangoSimon Willison
Ā 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
Ā 
Web App Security Horror Stories
Web App Security Horror StoriesWeb App Security Horror Stories
Web App Security Horror StoriesSimon Willison
Ā 
Web Security Horror Stories
Web Security Horror StoriesWeb Security Horror Stories
Web Security Horror StoriesSimon Willison
Ā 

More from Simon Willison (20)

How Lanyrd does Geo
How Lanyrd does GeoHow Lanyrd does Geo
How Lanyrd does Geo
Ā 
Cheap tricks for startups
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startups
Ā 
The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)
Ā 
Building Lanyrd
Building LanyrdBuilding Lanyrd
Building Lanyrd
Ā 
How we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphHow we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graph
Ā 
Web Services for Fun and Profit
Web Services for Fun and ProfitWeb Services for Fun and Profit
Web Services for Fun and Profit
Ā 
Tricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationTricks & challenges developing a large Django application
Tricks & challenges developing a large Django application
Ā 
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricAdvanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Ā 
How Lanyrd uses Twitter
How Lanyrd uses TwitterHow Lanyrd uses Twitter
How Lanyrd uses Twitter
Ā 
ScaleFail
ScaleFailScaleFail
ScaleFail
Ā 
Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approval
Ā 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
Ā 
Building crowdsourcing applications
Building crowdsourcing applicationsBuilding crowdsourcing applications
Building crowdsourcing applications
Ā 
Evented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesEvented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunnies
Ā 
Cowboy development with Django
Cowboy development with DjangoCowboy development with Django
Cowboy development with Django
Ā 
Crowdsourcing with Django
Crowdsourcing with DjangoCrowdsourcing with Django
Crowdsourcing with Django
Ā 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
Ā 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
Ā 
Web App Security Horror Stories
Web App Security Horror StoriesWeb App Security Horror Stories
Web App Security Horror Stories
Ā 
Web Security Horror Stories
Web Security Horror StoriesWeb Security Horror Stories
Web Security Horror Stories
Ā 

Recently uploaded

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
Ā 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
Ā 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
Ā 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
Ā 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
Ā 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
Ā 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
Ā 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
Ā 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
Ā 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
Ā 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
Ā 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
Ā 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
Ā 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo GarcĆ­a Lavilla
Ā 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
Ā 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
Ā 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
Ā 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
Ā 

Recently uploaded (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
Ā 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
Ā 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
Ā 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
Ā 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Ā 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
Ā 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Ā 
Hot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort Service
Hot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort ServiceHot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort Service
Hot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort Service
Ā 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
Ā 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
Ā 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
Ā 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Ā 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
Ā 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
Ā 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
Ā 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
Ā 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
Ā 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
Ā 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
Ā 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Ā 

A Re-Introduction to JavaScript

  • 1. http://www.ļ¬‚ickr.com/photos/tomsly/93947243/ - thomas_sly A (Re)-Introduction to JavaScript Simon Willison ETech, March 6th, 2005 1 1
  • 2. Coming up... ā€¢ Numbers, Strings and things ā€¢ Variables and Operators ā€¢ Control Structures ā€¢ Objects and Arrays ā€¢ Functions ā€¢ Object constructors and inheritance ā€¢ Inner functions and closures ā€¢ Memory Leaks... and more 2 2
  • 3. Book recommendation ā€¢ JavaScript: The Definitive Guide ā€“ by David Flanagan ā€¢ Comprehensive overview of the language in the first 20 chapters ā€¢ New edition out later this year 3 3
  • 4. More book recommendations ā€¢ For practical applications of this stuff: 4 4
  • 5. You will need... ā€¢ Firefox ā€“ Any web browser can run JavaScript, but Firefox has the best tools for developers ā€¢ Jesse Ruderman's 'shell' tool ā€“ http://www.squarefree.com/shell/ ā€¢ A text editor may come in handy too 5 5
  • 6. In the words of its creator JavaScript was a rushed little hack for Netscape 2 that was then frozen prematurely during the browser wars, and evolved significantly only once by ECMA. So its early flaws were never fixed, and worse, no virtuous cycle of fine-grained community feedback in the form of standard library code construction, and revision of the foundational parts of the language to better support the standard library and its common use-cases, ever occurred. 6 http://weblogs.mozillazine.org/roadmap/archives/2006/02/js_and_python_news.html 6
  • 7. http://www.ļ¬‚ickr.com/photos/kingcoyote/93491484/ - King Coyote The History of JavaScript (in 30 seconds) 7 7
  • 8. JavaScript was... Invented by Brendan Eich in 1995 for Netscape; originally called LiveScript, current name being an ill-fated marketing decision to tie in with Sun's newly released Java; adapted by Microsoft as JScript for IE 3 in 1996; standardised as ECMAScript in 1997; sort-of included in Flash as ActionScript; updated to ECMAScript 3rd edition in 1998 8 8
  • 9. Not quite general purpose ā€¢ No direct concept of input or output ā€¢ Runs within a host environment ā€“ Web browser ā€“ Adobe Acrobat ā€“ Photoshop ā€“ Windows Scripting Host ā€“ Yahoo! Widget Engine ā€“ and more... 9 9
  • 11. Reserved words break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public 11 11
  • 12. Style recommendations ā€¢ Avoid semi-colon insertion like the plague ;;; friends ā€¢ Declare variables religiously with 'var' ā€¢ Global variables are evil. Avoid them if you can. ā€¢ Indent consistently 12 12
  • 14. JavaScript types ā€¢ Numbers ā€¢ Strings ā€¢ Booleans ā€¢ Functions ā€¢ Objects 14 14
  • 15. JavaScript types (improved) ā€¢ Number ā€¢ String ā€¢ Boolean ā€¢ Object ā€“ Function ā€“ Array ā€“ Date ā€“ RegExp ā€¢ Null ā€¢ Undefined 15 15
  • 17. Numbers ā€¢ quot;double-precision 64-bit format IEEE 754 valuesquot; ā€¢ No such thing as an integer 0.1 + 0.2 = 0.30000000000000004 3 + 5.3 28 % 6 etc... ā€¢ Math namespace for advanced operations 17 17
  • 18. Math stuff ā€¢ Math.PI, Math.E, Math.LN10, Math.LN2, Math.LOG10E, Math.SQRT1_2, Math.SQRT2 ā€¢ Math.abs(x), Math.acos(x), Math.asin(x), Math.atan(x), Math.atan2(y, x), Math.ceil(x), Math.cos(x), Math.exp(x), Math.floor(x), Math.log(x), Math.max(x, ..), Math.min(x, ..), Math.pow(x, y), Math.random(), Math.round(x), Math.sin(x), Math.sqrt(x), Math.tan(x) 18 18
  • 19. parseInt (and parseFloat) ā€¢ parseInt converts a string to a number > parseInt(quot;123quot;); 123 > parseInt(quot;010quot;); Always specify the base 8 ā€¢ !? > parseInt(quot;010quot;, 10); 10 > parseInt(quot;11quot;, 2) 3 19 19
  • 20. NaN and Infinity > parseInt(quot;helloquot;, 10) NaN ā€¢ NaN is toxic > NaN + 5 NaN > isNaN(NaN) true ā€¢ Special values for Infinity and -Infinity: >1/0 > -1 / 0 Infinity -Infinity 20 20
  • 22. Strings ā€¢ Sequences of characters ā€¢ Sequences of unicode characters (16 bit) quot;u0020quot; ā€¢ A character is a string of length 1 > quot;helloquot;.length 5 ā€¢ Strings are objects! 22 22
  • 23. String methods > quot;helloquot;.charAt(0) h > quot;hello, worldquot;.replace(quot;helloquot;, quot;goodbyequot;) goodbye, world > quot;helloquot;.toUpperCase() HELLO 23 23
  • 24. More string methods s.charAt(pos) s.charCodeAt(pos) s.concat(s1, ..) s.indexOf(s1, start) s.lastIndexOf(s1, startPos) s.localeCompare(s1) s.match(re) s.replace(search, replace) s.search(re) s.slice(start, end) s.split(separator, limit) s.substring(start, end) s.toLowerCase() s.toLocaleLowerCase() s.toUpperCase() s.toLocaleUpperCase() 24 24
  • 25. Null and undefined ā€¢ null = deliberately no value ā€¢ undefined = no value assigned yet ā€“ Variables declared but not initialised ā€“ Object/array members that don't exist ā€“ (More on this later) 25 25
  • 26. Booleans ā€¢ Boolean type: true or false ā€¢ Everything else is quot;truthyquot; or quot;falsyquot; ā€¢ 0, quot;quot;, NaN, null, undefined are falsy ā€¢ Everything else is truthy ā€¢ Boolean operations: &&, || and ! ā€¢ Convert any value to it's boolean equivalent by applying not twice: > !!234 > !!quot;quot; true false 26 26
  • 27. http://www.ļ¬‚ickr.com/photos/antmoose/71277315/ - antmoose / Anthony M. Variables and operators 27 27
  • 28. Variable declaration ā€¢ New variables in JavaScript are declared using the var keyword: var a; var name = quot;simonquot;; ā€¢ If you declare a variable without assigning it to anything, its value is undefined. If you forget the var, you get a global variable. Never, ever do this - not even if you mean it. 28 28
  • 29. Operators Numeric operators: +, -, *, / and % ā€¢ Compound assignment operators: +=, -=, *=, /=, %= ā€¢ Increment and decrement: a++, ++a, b--, --b ā€¢ String concatenation: > quot;helloquot; + quot; worldquot; hello world 29 29
  • 30. Type coercion > quot;3quot; + 4 + 5 345 > 3 + 4 + quot;5quot; 75 ā€¢ Adding an empty string to something else converts it to a string. 30 30
  • 31. Comparison ā€¢ >, <, >=, <= work for numbers and strings ā€¢ Equality tests use == and != ... sort of > quot;dogquot; == quot;dogquot; true > 1 == true true ā€¢ === and !== avoid type coercion > 1 === true false > true === true true 31 31
  • 32. The typeof operator typeof v number 'number' string 'string' boolean 'boolean' function 'function' object 'object' array 'object' null 'object' undefined 'undefined' 32 32
  • 34. if statements var name = quot;kittensquot;; if (name == quot;puppiesquot;) { name += quot;!quot;; } else if (name == quot;kittensquot;) { name += quot;!!quot;; } else { name = quot;!quot; + name; } name == quot;kittens!!quot; 34 34
  • 35. while and do-while while (true) { // an infinite loop! } do { var input = get_input(); } while (inputIsNotValid(input)) 35 35
  • 36. for loops for (var i = 0; i < 5; i++) { // Will execute 5 times } 36 36
  • 37. switch statement ā€¢ Multiple branches depending on a number or string switch(action) { case 'draw': drawit(); break; case 'eat': eatit(); break; default: donothing(); } 37 37
  • 38. fall through switch(a) { case 1: // fallthrough case 2: eatit(); break; default: donothing(); } ā€¢ Deliberate labelling of fall through is good practise 38 38
  • 39. Switch expressions ā€¢ Expressions are allowed ā€¢ Comparisons take place using === switch(1 + 3): case 2 + 2: yay(); break; default: neverhappens(); } 39 39
  • 40. Short-circuit logic ā€¢ The && and || operators use short-circuit logic: they will execute their second operand dependant on the first. ā€¢ This is useful for checking for null objects before accessing their attributes: var name = o && o.getName(); ā€¢ Or for setting default values: var name = otherName || quot;defaultquot;; 40 40
  • 41. The tertiary operator ā€¢ One-line conditional statements var ok = (age > 18) ? quot;yesquot; : quot;noquot;; ā€¢ Easy to abuse; use with caution 41 41
  • 42. Exceptions try { // Statements in which // exceptions might be thrown } catch(error) { // Statements that execute // in the event of an exception } finally { // Statements that execute // afterward either way } throw new Error(quot;An error!quot;); throw quot;Another error!quot;; 42 42
  • 44. Objects ā€¢ Simple name-value pairs, as seen in: ā€“ Dictionaries in Python ā€“ Hashes in Perl and Ruby ā€“ Hash tables in C and C++ ā€“ HashMaps in Java ā€“ Associative arrays in PHP ā€¢ Very common, versatile data structure ā€¢ Name part is a string; value can be anything 44 44
  • 45. Basic object creation var obj = new Object(); ā€¢ Or: var obj = {}; ā€¢ These are semantically equivalent; the second is called object literal syntax and is more convenient. 45 45
  • 46. Property access obj.name = quot;Simonquot; var name = obj.name; ā€¢ Or... obj[quot;namequot;] = quot;Simonquot;; var name = obj[quot;namequot;]; ā€¢ Semantically equivalent; the second uses strings so can be decided at run-time (and can be used for reserved words) 46 46
  • 47. Object literal syntax var obj = { name: quot;Carrotquot;, quot;forquot;: quot;Maxquot;, details: { color: quot;orangequot;, size: 12 } } > obj.details.color > obj[quot;detailsquot;][quot;sizequot;] orange 12 47 47
  • 48. for (var attr in obj) ā€¢ You can iterate over the keys of an object: var obj = { 'name': 'Simon', 'age': 25}; for (var attr in obj) { print (attr + ' = ' + obj[attr]); } ā€¢ Don't attempt this with arrays (coming up next). There are safer ways of iterating over them. 48 48
  • 50. Arrays ā€¢ A special type of object: Keys are whole numbers, not strings. ā€¢ Use [] syntax, just like objects > var a = new Array(); > a[0] = quot;dogquot;; > a[1] = quot;catquot;; > a[2] = quot;henquot;; > a.length 3 50 50
  • 51. Array literals ā€¢ More convenient notation: > var a = [quot;dogquot;, quot;catquot;, quot;henquot;]; > a.length 3 51 51
  • 52. array.length > var a = [quot;dogquot;, quot;catquot;, quot;henquot;]; > a[100] = quot;foxquot;; > a.length 101 typeof a[90] == 'undefined' ā€¢ array.length is always one more than the highest index ā€¢ The safest way to append new items is: a[a.length] = item; 52 52
  • 53. Array iteration for (var i = 0; i < a.length; i++) { // Do something with a[i] } ā€¢ Improve this by caching a.length at start: for (var i = 0, j = a.length; i < j; i++) { // Do something with a[i] } 53 53
  • 54. Even better iteration for (var i = 0, item; item = a[i]; i++) { // Do something with item } ā€¢ This trick only works with arrays that are known not to contain falsy values. The following array will break with the above idiom: var a = [10, quot;dogquot;, false, quot;elephantquot;]; ā€¢ (Yes, you can have mixed content in arrays) 54 54
  • 55. Array methods a.toString(), a.toLocaleString(), a.concat(item, ..), a.join(sep), a.pop(), a.push(item, ..), a.reverse(), a.shift(), a.slice(start, end), a.sort(cmpfn), a.splice(start, delcount, [item]..), a.unshift([item]..) 55 55
  • 56. 3.2 2.4 1.6 0.8 .8 -4 -3.2 -2.4 -1.6 -0.8 0 0.8 1.6 2.4 3.2 4 4.8 -0.8 Functions -1.6 -2.4 -3.2 56 56
  • 57. Functions ā€¢ Don't get much simpler than this: function add(x, y) { var total = x + y; return total; } ā€¢ If nothing is explicitly returned, return value is undefined 57 57
  • 58. Arguments ā€¢ Parameters: quot;They're more like... guidelinesquot; ā€¢ Missing parameters are treated as undefined: > add() Nan // addition on undefined ā€¢ You can pass in more arguments than expected: > add(2, 3, 4) 5 // added the first two; 4 was ignored ā€¢ How is this behaviour useful? 58 58
  • 59. arguments ā€¢ The arguments special variable provides access to arguments as an array-like object function add() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { sum += arguments[i]; } return sum; } > add(2, 3, 4, 5) 14 59 59
  • 60. avg() ā€¢ More useful: an averaging function: function avg() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { sum += arguments[i]; } return sum / arguments.length; } 60 60
  • 61. Averaging an array? ā€¢ Our fancy multi-argument function isn't much good if our data is already in an array. Do we have to rewrite it? function avgArray(arr) { var sum = 0; for (var i = 0, j = arr.length; i < j; i++) { sum += arguments[i]; } return sum / arr.length; } 61 61
  • 62. Using avg() with an array ā€¢ That's not necessary: > avg.apply(null, [2, 3, 4, 5]) 3.5 ā€¢ Functions are objects with methods too! ā€¢ The apply method takes an array of argments as the second argument... ā€¢ We'll find out about the first argument a little later 62 62
  • 63. Anonymous functions ā€¢ The following is semantically equivalent to our earlier avg() function: var avg = function() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { sum += arguments[i]; } return sum / arguments.length; } 63 63
  • 64. The block scope trick ā€¢ Block scope is a feature of C where every set of braces defines a new scope. It can be simulated in JavaScript: var a = 1; var b = 2; (function() { var b = 3; a += b; })(); >a 4 >b 2 64 64
  • 65. Recursive functions function countChars(elm) { if (elm.nodeType == 3) { // TEXT_NODE return elm.nodeValue.length; } var count = 0; for (var i = 0, child; child = elm.childNodes[i]; i++) { count += countChars(child); } return count; } 65 65
  • 66. arguments.callee ā€¢ arguments.callee is the current function: var charsInBody = (function(elm) { if (elm.nodeType == 3) { // TEXT_NODE return elm.nodeValue.length; } var count = 0; for (var i = 0, child; child = elm.childNodes[i]; i++) { count += arguments.callee(child); } return count; })(document.body); 66 66
  • 67. arguments.callee to save state ā€¢ This function remembers how many times it has been called: function counter() { if (!arguments.callee.count) { arguments.callee.count = 0; } return arguments.callee.count++; } > counter() 0 > counter() 1 67 67
  • 69. Functions and objects function makePerson(first, last) { return { first: first, last: last } } function personFullName(person) { return person.first + ' ' + person.last; } function personFullNameReversed(person) { return person.last + ', ' + person.first } 69 69
  • 70. Functions and objects (II) > s = makePerson(quot;Simonquot;, quot;Willisonquot;); > personFullName(s) Simon Willison > personFullNameReversed(s) Willison, Simon ā€¢ Surely we can attach functions to the objects themselves? 70 70
  • 71. Methods, first try function makePerson(first, last) { return { first: first, last: last, fullName: function() { return this.first + ' ' + this.last; }, fullNameReversed: function() { return this.last + ', ' + this.first; } } } 71 71
  • 72. Using methods > s = makePerson(quot;Simonquot;, quot;Willisonquot;) > s.fullName() Simon Willison > s.fullNameReversed() Willison, Simon 72 72
  • 73. dot notation is required > s = makePerson(quot;Simonquot;, quot;Willisonquot;) > var fullName = s.fullName; > fullName() undefined undefined ā€¢ If you call a function without using dot notation, 'this' is set to the global object. In the browser, this is the same as 'window'. 73 73
  • 74. Constructors function Person(first, last) { this.first = first; this.last = last; this.fullName = function() { return this.first + ' ' + this.last; } this.fullNameReversed = function() { return this.last + ', ' + this.first; } } var s = new Person(quot;Simonquot;, quot;Willisonquot;); 74 74
  • 75. new ā€¢ 'new' creates a new empty object and calls the specified function with 'this' set to that object. ā€¢ These constructor functions should be Capitalised, as a reminder that they are designed to be called using 'new' ā€¢ This is key to understanding JavaScript's object model 75 75
  • 76. Sharing methods function personFullName() { return this.first + ' ' + this.last; } function personFullNameReversed() { return this.last + ', ' + this.first; } function Person(first, last) { this.first = first; this.last = last; this.fullName = personFullName; this.fullNameReversed = personFullNameReversed; } 76 76
  • 77. Person.prototype function Person(first, last) { this.first = first; this.last = last; } Person.prototype.fullName = function() { return this.first + ' ' + this.last; } Person.prototype.fullNameReversed = function() { return this.last + ', ' + this.first; } 77 77
  • 78. instanceof ā€¢ The instanceof operator can be used to test the type of an object, based on its constructor (and prototype hierarchy, explained in the next section). var a = [1, 2, 3]; a instanceof Array true a instanceof Object true a instanceof String false 78 78
  • 80. Adding to an existing set of objects > s = new Person(quot;Simonquot;, quot;Willisonquot;); > s.firstNameCaps(); TypeError on line 1: s.firstNameCaps is not a function > Person.prototype.firstNameCaps = function() { return this.first.toUpperCase() } > s.firstNameCaps() SIMON 80 80
  • 81. Extending core objects > var s = quot;Simonquot;; > s.reversed() TypeError: s.reversed is not a function > String.prototype.reversed = function() { var r = ''; for (var i = this.length - 1; i >= 0; i--){ r += this[i]; } return r; } > s.reversed() nomiS > quot;This can now be reversedquot;.reversed() desrever eb won nac sihT 81 81
  • 82. Object.prototype ā€¢ All prototype chains terminate at Object.prototype ā€¢ Its methods include toString(), which we can over-ride: > var s = new Person(quot;Simonquot;, quot;Willisonquot;); >s [object Object] > Person.prototype.toString = function() { return '<Person: ' + this.fullName() + '>'; } >s <Person: Simon Willison> 82 82
  • 83. Perils of modifying Object.prototype ā€¢ Remember for (var attr in obj)? ā€¢ It will include stuff that's been newly added to Object.prototype ā€¢ This stupid behaviour is sadly baked in to the language ā€¢ Some libraries (Prototype is a prime offender) do it anyway 83 83
  • 84. So what about inheritance? ā€¢ Problem: JavaScript is a prototype-based language, but it pretends to be a class-based language ā€¢ As a result, it doesn't do either very well ā€¢ Inheritance doesn't quite behave how you would expect 84 84
  • 85. Here's a special kind of person function Geek() { Person.apply(this, arguments); this.geekLevel = 5; } Geek.prototype = new Person(); Geek.prototype.setLevel = function(lvl) { this.geekLevel = lvl; } Geek.prototype.getLevel = function() { return this.geekLevel; } > s = new Geek(quot;Simonquot;, quot;Willisonquot;) > s.fullName() Simon Willison > s.getLevel() 5 85 85
  • 86. new Person()? ā€¢ We're using an instance of the Person object as our prototype ā€¢ We have to do this, because we need to be able to modify our prototype to add new methods that are only available to Geek instances ā€¢ This is counter-intuitive and, well, a bit dumb 86 86
  • 87. Solutions? ā€¢ Design classes with inheritance in mind - don't do anything important in the constructor (that might break if you create an empty instance for use as a prototype) ā€¢ Use one of the many workarounds ā€“ Prototype's Class.create() ā€“ The stuff you get by searching for quot;javascript inheritancequot; on the Web 87 87
  • 89. Functions are first-class objects ā€¢ In English... ā€“ A function is just another object ā€“ You can store it in a variable ā€“ You can pass it to another function ā€“ You can return it from a function 89 89
  • 90. VAT VAT is England's national sales tax - 17.5% var prices = [10, 8, 9.50]; var pricesVat = []; for (var i = 0; i < prices.length; i++) { pricesVat[i] = prices[i] * 1.175; } 90 90
  • 91. arrayMap function arrayMap(array, func) { var result = []; for (var i = 0; i < array.length; i++) { result[i] = func(array[i]); } return result; } function calcVat(price) { return price * 1.175; } var prices = [10, 8, 9.50]; pricesVat = arrayMap(prices, calcVat); 91 91
  • 92. salesTaxFactory What if we want to calculate sales tax at 4%? function salesTaxFactory(percent) { function func(price) { return price + (percent / 100) * price; } return func; } calcVat = salesTaxFactory(17.5); calc4 = salesTaxFactory(4); pricesVat = arrayMap(prices, calcVat); prices4 = arrayMay(prices, calc4); 92 92
  • 93. An operation factory function makeOp(op, y) { switch (op) { case '+': return function(x) { return x + y }; case '-': return function(x) { return x - y }; case '/': return function(x) { return x / y }; case '*': return function(x) { return x * y }; default: return function(x) { return x }; } } var third = makeOp('/', 3); var dbl = makeOp('*', 2); print(third(24)); print(dbl(5)); 93 93
  • 94. Closures ā€¢ The previous code was an example of closures in action ā€¢ A closure is a function that has captured the scope in which it was defined ā€¢ Actually, functions in JavaScript have a scope chain (similar to the prototype chain) 94 94
  • 95. What does this do? function openLinksInNewWindows() { for (var i = 0; i < document.links.length; i++) { document.links[i].onclick = function() { window.open(document.links[i].href); return false; } } } ā€¢ The onclick function is a closure which refers back to the original scope; it does NOT retain a copy of the i variable at the time the function was created. By the time the onclick function is executed, i will be the last value assigned by the loop. 95 95
  • 97. Namespace pollution ā€¢ JavaScript shares a single global namespace ā€¢ Itā€™s easy to clobber other peopleā€™s functions and variables ā€¢ Itā€™s easy for other people to clobber yours ā€¢ The less code affecting the global namespace the better 97 97
  • 98. The singleton pattern var simon = (function() { var myVar = 5; // Private variable function init(x) { // ... can access myVar and doPrivate } function doPrivate(x) { // ... invisible to the outside world } function doSomething(x, y) { // ... can access myVar and doPrivate } return { 'init': init, 'doSomething': doSomething } })(); simon.init(x); 98 98
  • 99. Singleton benefits ā€¢ Singleton lets you wrap up a complex application with dozens of functions up in a single, private namespace - a closure ā€¢ This lets you expose only the functions that make up your application's external interface 99 99
  • 101. Internet Explorer sucks ā€¢ To understand memory leaks, you have to understand a bit about garbage collection ā€¢ Stuff gets freed up automatically when it is no longer in use (both JavaScript objects and host objects, such as DOM nodes) ā€¢ IE uses different garbage collectors for JS and for the DOM, and can't handle circular references between them 101 101
  • 102. This leaks function leak() { var div = document.getElementById('d'); div.obj = { 'leak': div } } ā€¢ Call it enough times and IE will crash 102 102
  • 103. This also leaks function sneakyLeak() { var div = document.getElementById('d'); div.onclick = function() { alert(quot;hi!quot;); } } ā€¢ Why? Spot the closure! 103 103
  • 104. Difficulties ā€¢ These things can be very hard to detect - especially in large, complex applications where a cycle might occur over many nodes and JavaScript objects ā€¢ One solution: function noLeak() { var div = document.getElementById('d'); div.onclick = function() { alert(quot;hi!quot;); } div = null; } 104 104
  • 105. More solutions ā€¢ Most popular JavaScript libraries have systems for attaching and detaching events ā€¢ Many of these can automatically free event references when the page is unloaded ā€¢ Use these, but always be aware of the problem 105 105
  • 107. Performance tips ā€¢ De-reference complex lookups var s = document.getElementById('d').style; s.width = '100%'; s.color = 'red'; // ... s.display = 'block'; ā€¢ ... especially inside loops var lookup = foo.bar.bav; for (var i = 0; i < 1000; i++) { lookup.counter += someCalc(); } 107 107
  • 109. Suggested libraries ĀÆĀÆ dojotoolkit.org developer.yahoo.net/yui/ prototype.conio.net mochikit.com script.aculo.us 109 109
  • 110. Tell Alex I told you this... ā€¢ Everything in JavaScript is an Object. Even functions ā€¢ Every object is always mutable ā€¢ The dot operator is equivalent to de-referencing by hash (e.g., foo.bar === foo[quot;barquot;]) ā€¢ The new keyword creates an object that class constructors run inside of, thereby imprinting them ā€¢ Functions are always closures (combine w/ previous rule to create OOP) ā€¢ The this keyword is relative to the execution context, not the declaration context ā€¢ The prototype property is mutable 110 110