SlideShare une entreprise Scribd logo
1  sur  101
Télécharger pour lire hors ligne
JavaScript Beyond
     jQuery
     John Wilander




                     @johnwilander
shouldilearnjavascript.com




                             @johnwilander
Part 1: Typing



                 @johnwilander
Java
                       Types
Primitive:
byte, short, int, long, float, double,
boolean, char

The rest is objects, so called reference types
JavaScript

 Primitive:
 string, number, boolean, function,
 undefined

 The rest is object
                                                 @johnwilander
Java
               Types
Primitive:
byte, short, int, long, float, double,
boolean, char


JavaScript

 Primitive:
 string, number, boolean, function,
 undefined


                                      @johnwilander
Java
               Types
Primitive:
byte, short, int, long, float, double,
boolean, charnot
        Strings are
       general objects,
        they're a type
JavaScript

 Primitive:
 string, number, boolean, function,
 undefined


                                      @johnwilander
Java
                 Types
Primitive:Only one type
byte, for numbers, i.e. long, float, double,
         short, int,
          no difference
boolean, char
        between integers
           or decimals
JavaScript

 Primitive:
 string, number, boolean, function,
 undefined


                                         @johnwilander
Java
                Types
Primitive:
byte, short, int, long, float, double,
boolean, char           Functions are full
                       objects with their
                           own type
JavaScript

 Primitive:
 string, number, boolean, function,
 undefined


                                       @johnwilander
Java
               Types
Primitive:
byte, short, int, long, float, double,
            JavaScript's
boolean, char
             version of
           uninitialized is
JavaScript
           undefined
 Primitive:
 string, number, boolean, function,
 undefined


                                      @johnwilander
Java
       Static vs Dynamic Typing
Static typing:
String name;         Variables have types
name = ”John”;       Values have types
name = 34;           Variables cannot change type

JavaScript

 Dynamic typing:
 var name;       Variables have no types
 name = ”John”; Values have types
 name = 34;      Variables change type dynamically
                                                    @johnwilander
Dynamic Typing
JavaScript




             var name = ”John”;


               Variables have   Values have types
                 no types
                                                    @johnwilander
Strong vs Weak Typing




                        @johnwilander
Strong vs Weak Typing

   Strong !== good
    Weak !== bad



                        @johnwilander
Java
         Strong vs Weak Typing
int intVar = 4;      Pretty strong typing
"" + intVar;         Implicit type conversion
intVar + 0.0;        Implicit, widening type conv.
intVar + (int)0.0;   Explicit type conversion
intVar + null;       Not allowed
JavaScript

 var dynVar = 4;     Very weak typing
 dynVar + "";        Implicit type conversion
 dynVar + null;      Implicit type conversion
 dynVar + [];        Implicit type conversion
 dynVar + [0];       Implicit type conversion
                                                @johnwilander
Type Safe
           ≈
no type errors at runtime


                            @johnwilander
John's Conclusion

   Java is a statically, strongly typed
   language with decent type safety


JavaScript is a dynamically, weakly typed
    language with decent type safety



                                            @johnwilander
Object Orientation



                     @johnwilander
Java: Classes & Objects
                  Object
         Class     Object
                               Executing
Source               Object      code


         Class     Singleton


                                   @johnwilander
JavaScript: Functions,
     Object & Prototypes
                     Object
         Prototype    Object
                                 Executing
Source                  Object     code


         Function     Function


                                     @johnwilander
JavaScript: Functions,
     Object & Prototypes
                       Object
           Prototype

                        Object
                                   Executing
Source                    Object     code
         Function
         Anonymous
          closures      Function
          Modules
                                       @johnwilander
Keywords in JavaScript

                                                                    Statistics from:
                                                                    jQuery
                                                                    jQuery.Mobile
                                                                    Prototype
                                                                    Ext JS
                                                                    MooTools
                                                                    Backbone	

 	

                                                                    Underscore

   http://ariya.ofilabs.com/2012/03/most-popular-javascript-keywords.html      @johnwilander
Keywords in JavaScript
                       Functions,
                       functions,
                       functions
       Seldom new




          Almost never
         classes as types
                                    @johnwilander
Java: Extension by
   Inheritance
      Subclass

                 extends


       Super
        class



                       @johnwilander
Java: Subtyping by
   Inheritance
       Super
        type
                 extends


       Subtype




                       @johnwilander
Through inheritance
 Java classes get larger
 in terms of functions
           and
smaller in terms of type
     (more specific)

                           @johnwilander
In JavaScript
     extension
        and
     subtyping
are separate things


                      @johnwilander
Why do we want to
      subtype?
Because we think in
      terms of
 static typing and
   is-a-relations
                      @johnwilander
Static Typing and
             Subtyping
Java




       public void doPurchase(Item item)




                          Accepts Item
                       or subtypes to Item
                                             @johnwilander
Dynamic Typing
JavaScript




             public void doPurchase(Item item)




                                                 @johnwilander
Dynamic Typing
JavaScript




             public void doPurchase(Item item)




                                                 @johnwilander
Dynamic Typing
JavaScript




             public void doPurchase(Item item)




                                                 @johnwilander
Dynamic Typing
JavaScript




             public void doPurchase(Item item)




                                                 @johnwilander
Dynamic Typing
JavaScript




             function doPurchase(item)__




                           Accepts anything
                            ... or nothing
                                              @johnwilander
Dynamic Typing
JavaScript




             function doPurchase(item)__




                    Can return anything
                       ... or nothing
                                           @johnwilander
Part 2: To start a
JavaScript program


                       @johnwilander
<html>
            JavaScript and Web
<head>
  <script src=”js/main.js”></script>
  <script>
         var JW = {};
         // More code
  </script>
</head>
<body>
  <button onclick="document.getElementById('field2').value=
document.getElementById('field1').value">Copy text</button>
  <div>
    Some information
  </div>
  <script>
         JW.calcPrice = function(price, vat) { //… };
  </script>
  <script src=”http://3rdparty.com/trackUsers.js”></script>
</body>
</html>
                                                              @johnwilander
JavaScript and Web
<html>
<head>
                                     Script from file in <head>
  <script src=”js/main.js”></script>  Synchronous loading and
  <script>
         var JW = {};                         execution
         // More code
  </script>
</head>
<body>
  <button onclick="document.getElementById('field2').value=
document.getElementById('field1').value">Copy text</button>
  <div>
    Some information
  </div>
  <script>
         JW.calcPrice = function(price, vat) { //… };
  </script>
  <script src=”http://3rdparty.com/trackUsers.js”></script>
</body>
</html>
                                                              @johnwilander
<html>
            JavaScript and Web
<head>
  <script src=”js/main.js”></script>   Inlined script in <head>
  <script>
         var JW = {};                   Synchronous execution
         // More code
  </script>
                                        before DOM is loaded
</head>
<body>
  <button onclick="document.getElementById('field2').value=
document.getElementById('field1').value">Copy text</button>
  <div>
    Some information
  </div>
  <script>
         JW.calcPrice = function(price, vat) { //… };
  </script>
  <script src=”http://3rdparty.com/trackUsers.js”></script>
</body>
</html>
                                                              @johnwilander
<html>
            JavaScript and Web
<head>
  <script src=”js/main.js”></script>
  <script>
         var JW = {};
         // More code
  </script>                             Script directly in HTML,
</head>
<body>                                  executed on click event
  <button onclick="document.getElementById('field2').value=
document.getElementById('field1').value">Copy text</button>
  <div>
    Some information
  </div>
  <script>
         JW.calcPrice = function(price, vat) { //… };
  </script>
  <script src=”http://3rdparty.com/trackUsers.js”></script>
</body>
</html>
                                                              @johnwilander
<html>
            JavaScript and Web
<head>
  <script src=”js/main.js”></script>
  <script>
         var JW = {};
         // More code
  </script>
</head>
<body>
  <button onclick="document.getElementById('field2').value=
                                       Inlined script in <body>
document.getElementById('field1').value">Copy text</button>
  <div>
    Some information                       Executed when the
  </div>
  <script>                                  parser gets here
         JW.calcPrice = function(price, vat) { //… };
  </script>
  <script src=”http://3rdparty.com/trackUsers.js”></script>
</body>
</html>
                                                              @johnwilander
<html>
            JavaScript and Web
<head>
  <script src=”js/main.js”></script>
  <script>
         var JW = {};
         // More code
  </script>
</head>
<body>
  <button onclick="document.getElementById('field2').value=
document.getElementById('field1').value">Copy text</button>
  <div>
    Some information                 Script from file in <body>
  </div>
  <script>                           Loaded and executed
                                     synchronously
         JW.calcPrice = function(price, vat) { //… };
  </script>
  <script src=”http://3rdparty.com/trackUsers.js”></script>
</body>
</html>
                                                              @johnwilander
Good Practice:

1. All JavaScript on file.

2. All statically loaded
JavaScript in one block.
                            @johnwilander
Dynamic Loading
(function(){
 var oldFirstScript =
   document.getElementsByTagName('script')[0];
     newScript =
   document.createElement('script'),

 newScript.async = true;
 newScript.src = 'js/script.js';

 oldFirstScript.parentNode.insertBefore(
   newScript, oldFirstScript);
}());

                                           @johnwilander
OK, that's loading.
But I want to start.


                       @johnwilander
Java
             In the Beginning

public static void main(String[] args)


JavaScript



 (function(){}());

 window.someGlobalFunction();

                                   @johnwilander
Self-Invoking Functions
Anonymous, self-invoking with parameter
(function(me) {
  // Code
}('John'));

Anonymous, self-invoking without parameter
(function() {
  // Code
}());


                                             @johnwilander
Part 4: Variables



                    @johnwilander
JavaScript
                  Scope
 var GLOB = {};

 GLOB.func = function(array) {
    var local = …;
    …
    for (var i=0; i<array.length; i++){
      …
      var temp = array[i];
    }
 };


                                     @johnwilander
JavaScript
                  Scope
 var GLOB = {};

 GLOB.func = function(array) {
    var local = …, i, temp;
    …
    for (i=0; i<array.length; i++){
      …
      temp = array[i];
    }
 };


                                      @johnwilander
JavaScript
                    Scope
 var GLOB = {};

 GLOB.func = function(array) {
    var local = …, i, temp;
    …
    for (i=0; There are only two variable scopes:
               i<array.length; i++){
      …       Global or local function scope.
      temp = array[i];
    }         All local variables are hoisted to
 };           the top of the function.

                                               @johnwilander
JavaScript
              Closure
 (function(array) {
   var i, temp;
   …
   for (i=0; i<array.length; i++){
     …
     temp = array[i];
   }
 }([1, 2, 3]));




                                     @johnwilander
JavaScript
                 Closure
 (function(array) {
   var i, temp;
   …
   for (i=0; i<array.length; i++){
     …
     temp =Aarray[i]; its scope and its
              closure keeps
   }       context during its life span.
 }([1, 2, 3]));
           A reference ending up inside the
           closure (array above) will keep
           its value inside the closure.
                                              @johnwilander
JavaScript
             Closure Pitfall
 for(i=0; i<pages.length; i++) {
   var page = pages[i];
   pageElement.load(page.url,
     function() {
       launchForm(page.form);
     });
 }




                                   @johnwilander
JavaScript
             Closure Pitfall
 for(i=0; i<pages.length; i++) {
   var page = pages[i];
   pageElement.load(page.url,
     function() {
       launchForm(page.form);
     });
                  Callback function since
 }
                  pageElement.load()
                  is asynchronous



                                            @johnwilander
JavaScript
             Closure Pitfall
 for(i=0; i<pages.length; i++) {
   var page = pages[i];
   pageElement.load(page.url,
     function() {
              page is hoisted and thus gets
       launchForm(page.form);
     });      a new value for each iteration
 }




                                               @johnwilander
JavaScript
             Closure Pitfall
 var page;
 for(i=0; i<pages.length; i++) {
   page = pages[i];
   pageElement.load(page.url,
              page is hoisted and thus gets
     function() {
       launchForm(page.form);iteration
              a new value for each
     });
 }




                                              @johnwilander
JavaScript
             Closure Pitfall
 var page;
 for(i=0; i<pages.length; i++) {
   page = pages[i];
   pageElement.load(page.url,
     function() {
       launchForm(page.form);
     });        When the callback is run page
 }              will refer to
                pages[pages.length-1]
                or at least another value than
                intended.
                                           @johnwilander
JavaScript
             Closure Pitfall
 var page;
 for(i=0; i<pages.length; i++) {
   page = pages[i];
   pageElement.load(page.url,
     function() {
       launchForm(page.form);
     });
 }




                                   @johnwilander
Making Use of Closures
JavaScript

 var page;
 for(i=0; i<pages.length; i++) {
   page = pages[i];
   (function(page) {
     pageElement.load(page.url,
       function() {
           launchForm(page.form);
       }
     });
   })(page);
 }
                                    @johnwilander
Making Use of Closures
JavaScript

 var page;
 for(i=0; i<pages.length; i++) {
   page = pages[i];
   (function(page) {
     pageElement.load(page.url,
       function() {
           launchForm(page.form);
       }
              We bind page to a new closure
     });
   })(page); so that the callback refers
 }            correctly

                                          @johnwilander
With self-invoking functions,
 scope, and closures we are ready for
  the most important design pattern:

Part 5: The Crockford
        Module
          or
    Module Pattern
                                        @johnwilander
JavaScript

 JW.cache = (function(){}());




                                @johnwilander
JavaScript

 JW.cache = (function(){
   return {};
 }());




                           @johnwilander
JavaScript

 JW.cache = (function(){
   return {
     getPatient:
       function(personnummer) {

             }
   };
 }());




                                  @johnwilander
JavaScript

 JW.cache = (function(){
   var cache = {};
   return {
     getPatient:
       function(personnummer) {

             }
   };
 }());




                                  @johnwilander
JavaScript

 JW.cache = (function(){
   var cache = {};
   return {
      getPatient:
        function(personnummer) {
          var res=cache[personnummer];
          // Check if fresh
          // Return
        }
   };
 }());




                                     @johnwilander
JavaScript

 JW.cache = (function(){
   var cache = {};
   return {
      getPatient:
        function(personnummer) {
          var res=cache[personnummer];
          if(_isValid(res)) {
            return res.patient;
          } else {
            // Handle cache miss
          }
        }
   };
 }());

                                     @johnwilander
JavaScript

 JW.cache = (function(){
   var cache = {},
       _isValid = function(res) {

          }
      return {
        getPatient:
          function(personnummer) {
            var res=cache[personnummer];
            if(_isValid(res)) {
               return res.patient;
            } else {
               // Handle cache miss
            }
          }
                                       @johnwilander
JavaScript

 JW.cache = (function(){
   var cache = {},
       _isValid(res) {
         return !res ? false :
          (Date.now() - res.timestamp)
          <= 60000; // One minute
       }
   return {
     getPatient:
       function(personnummer) {
         var res=cache[personnummer];
         if(_isValid(res)) {
            return res.patient;
         } else {
            // Handle cache miss
                                    @johnwilander
JavaScript

 JW.cache = (function(){
   var cache = {},
       _isValid(res) {
         return !res ? false :
          (Date.now() - res.timestamp)
          <= 60000; // One minute
       }
   return { We can have (closure) private
             variables and functions
     getPatient:
       function(personnummer) {
         var res=cache[personnummer];
         if(_isValid(res)) {
           return res.patient;
         } else {
           // Handle cache miss
                                       @johnwilander
JavaScript

 Crockford = (function(initParam) {
   var privVar1, privVar2,
       _privFunc1 = function() {

                 },
                 _privFunc2 = function() {

          };
      return {
        pubVar1: ”value”,
        pubFunc1: function() {

             }
   };
 }(initParam));
                                             @johnwilander
Part 6:
Named Parameters


                   @johnwilander
Java
             Method Signatures
public void execPurchase(int, String,
String, boolean, User)



JavaScript

 function execPurchase(price, item,
 discountCode, wantsSpam, user)



                                      @johnwilander
Java
             Method Signatures
builder = new Purchase.Builder();
Purchase purchase =
     builder.setPrice(9900)
     .setItem(”cap”).wantsSpam(false)
     .setUser(user).build();
JavaScript

 function execPurchase(purchase) {
   purchase.price …
   purchase.item …
   purchase.wantsSpam …
   purchase.user …
                                     @johnwilander
Part 7: Asynchronous
  Module Definition
(AMD) with require.js

                        @johnwilander
Concatenate
 and minify




              @johnwilander
Concatenate
  and minify



You may want to separate
third party code to be able
to cache it harder.

                              @johnwilander
Concatenate
  and minify



The goal is to mimimize the
number of HTTP requests and
the size of data over the wire.

                             @johnwilander
Tools for Concatenation
     and Minification

• Google Closure Compiler
• UglifyJS
• require.js
  Concatenates and minifies with Closure
  Compiler or UglifyJS



                                          @johnwilander
require.js – import and
namespace in JavaScript


                      @johnwilander
require([
  "backbone",
  "underscore",
  "models/CartModel",
  "text!templates/CartItem.html"],
  function (Backbone, _, CartModel,
            cartItemTemplate) {

  // Code dependent on Backbone etc

});



                                      @johnwilander
paths : {
        jquery : "vendor/jquery.min",
        backbone : "../components/backbone/backbone-min",
        underscore : "../components/underscore/underscore"
      }
                                                     main.js
require([
  "backbone",
  "underscore",
  "models/CartModel",
  "text!templates/CartItem.html"],
  function (Backbone, _, CartModel,
            cartItemTemplate) {

  // Code dependent on Backbone etc

});



                                                     @johnwilander
File system, like Java packages

require([
  "backbone",
  "underscore",
  "models/CartModel",
  "text!templates/CartItem.html"],
  function (Backbone, _, CartModel,
            cartItemTemplate) {

  // Code dependent on Backbone etc

});



                                                   @johnwilander
require([
  "backbone",        Local name, like
  "underscore",      dependency injection
  "models/CartModel",
  "text!templates/CartItem.html"],
  function (Backbone, _, CartModel,
            cartItemTemplate) {

  var model = new CartModel();

});



                                            @johnwilander
Define new modules
   define([
     "backbone",
     "underscore",
     "models/CartModel",
     "text!templates/CartItem.html"],
     function (Backbone, _, CartModel,
               cartItemTemplate) {

     var CartItemView = …;

     …

     return CartItemView;
   });

                                         @johnwilander
CartItemView.js




                  @johnwilander
index.html without
       require.js or the like
<head>
  <script   src="js/lib/jquery-1.9.0.min.js"></script>
  <script   src="js/lib/jquery-encoder-0.1.0.js"></script>
  <script   src="js/base.js"></script>
  <script   src="js/JW/util/util.js"></script>
  <script   src="js/JW/personnummer/Personnummer.js"></script>
  <script   src="js/JW/patient/Patient.js"></script>
  …
  <script   src="js/JW/cache/cache.js"></script>
  <script   src="js/JW/proxy/proxy.js"></script>
  <script   src="js/JW/gui/gui.js"></script>
</head>

                              … manually, in the right order.

                                                            @johnwilander
index.html with
                require.js
<head>
  <script data-main="scripts/main" src="scripts/require.js" >
  </script>
</head>




                                                          @johnwilander
index.html with
                require.js
<head>
  <script data-main="scripts/main" src="scripts/require.js" >
  </script>
</head>
         require.config({
           …
           paths : {
             jquery : "vendor/jquery.min",
             backbone : "../components/backbone/backbone-min",
             underscore : "../components/underscore/underscore"
           }
         });

        require(["app"], function (App) {
          App.start();
        });
                                                        main.js
                                                          @johnwilander
Reference
Documentation
        Always
  developer.mozilla.org
       Never
  www.w3schools.com
         Why?
      w3fools.com


                          @johnwilander
The Stream
 http://javascriptweekly.com/

    @javascript_news
@BrendanEich @littlecalculist
@addy_osmani @addyosmani
 @paul_irish @badass_js
  @rwaldron @slicknet
 @kangax @unscriptable
        @sthlmjs

                                @johnwilander
dojo-release-1.8.3.zip 11 Mb



  ext-4.1.1a-gpl.zip 45,7 Mb
  ext-all.js 1 Mb




       yui_3.8.1.zip 28,1 Mb


             @joakimkemeny & @johnwilander
Simplified
Dom api     Templates
 & shims




Widgets       MVC



                        @joakimkemeny & @johnwilander
underscore
Modernizr
 jQuery       Simplified
              Dom api     Templates
               & shims




              Widgets       MVC



                                      @joakimkemeny & @johnwilander
Handlebars

                                   Mustach
Simplified
Dom api     Templates
 & shims




Widgets       MVC



                        @joakimkemeny & @johnwilander
Simplified
Dom api     Templates
 & shims
                                  Ember
                                Backbone
                                  angular

Widgets       MVC



                        @joakimkemeny & @johnwilander
Simplified
Dom api     Templates
 & shims




Widgets       MVC
                                      Spine


                        @joakimkemeny & @johnwilander
Simplified
            Dom api     Templates
             & shims




            Widgets       MVC
Bootstrap
jQuery UI
                                    @joakimkemeny & @johnwilander
Simplified
         Dom api     Templates
          & shims
Ext JS
Dojo
YUI

         Widgets       MVC



                                 @joakimkemeny & @johnwilander
All-in-one frameworks are
best suited for newly
written single-purpose
applications without
mashup behavior.




                            @joakimkemeny & @johnwilander
Micro frameworks are
better if you need to
integrate legacy code, some
nifty CMS product, or if you
have logic/content from
third parties.

Micro frameworks don't
”take over” you application.


                               @joakimkemeny & @johnwilander

Contenu connexe

En vedette

Haskell - Being lazy with class
Haskell - Being lazy with classHaskell - Being lazy with class
Haskell - Being lazy with classTiago Babo
 
OCamlOScope: a New OCaml API Search
OCamlOScope: a New OCaml API SearchOCamlOScope: a New OCaml API Search
OCamlOScope: a New OCaml API SearchJun Furuse
 
Erlang/Sapiens
Erlang/SapiensErlang/Sapiens
Erlang/Sapiensdarach
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingMario Fusco
 
Purely Functional I/O
Purely Functional I/OPurely Functional I/O
Purely Functional I/OC4Media
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediZeroTurnaround
 
Object Oriented Programming vs Functional Programming - Valencia.rb
Object Oriented Programming vs Functional Programming - Valencia.rbObject Oriented Programming vs Functional Programming - Valencia.rb
Object Oriented Programming vs Functional Programming - Valencia.rbDaniel Pecos Martínez
 
OO Development 1 - Introduction to Object-Oriented Development
OO Development 1 - Introduction to Object-Oriented DevelopmentOO Development 1 - Introduction to Object-Oriented Development
OO Development 1 - Introduction to Object-Oriented DevelopmentRandy Connolly
 

En vedette (8)

Haskell - Being lazy with class
Haskell - Being lazy with classHaskell - Being lazy with class
Haskell - Being lazy with class
 
OCamlOScope: a New OCaml API Search
OCamlOScope: a New OCaml API SearchOCamlOScope: a New OCaml API Search
OCamlOScope: a New OCaml API Search
 
Erlang/Sapiens
Erlang/SapiensErlang/Sapiens
Erlang/Sapiens
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Purely Functional I/O
Purely Functional I/OPurely Functional I/O
Purely Functional I/O
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila Szegedi
 
Object Oriented Programming vs Functional Programming - Valencia.rb
Object Oriented Programming vs Functional Programming - Valencia.rbObject Oriented Programming vs Functional Programming - Valencia.rb
Object Oriented Programming vs Functional Programming - Valencia.rb
 
OO Development 1 - Introduction to Object-Oriented Development
OO Development 1 - Introduction to Object-Oriented DevelopmentOO Development 1 - Introduction to Object-Oriented Development
OO Development 1 - Introduction to Object-Oriented Development
 

Similaire à JavaScript Beyond jQuery (Jfokus 2013)

Kevin Whinnery: Write Better JavaScript
Kevin Whinnery: Write Better JavaScriptKevin Whinnery: Write Better JavaScript
Kevin Whinnery: Write Better JavaScriptAxway Appcelerator
 
Write Better JavaScript
Write Better JavaScriptWrite Better JavaScript
Write Better JavaScriptKevin Whinnery
 
Write Better JavaScript
Write Better JavaScriptWrite Better JavaScript
Write Better JavaScriptKevin Whinnery
 
WDB005.1 - JavaScript for Java Developers (Lecture 1)
WDB005.1 - JavaScript for Java Developers (Lecture 1)WDB005.1 - JavaScript for Java Developers (Lecture 1)
WDB005.1 - JavaScript for Java Developers (Lecture 1)Igor Khotin
 
Javascript omg!
Javascript omg!Javascript omg!
Javascript omg!bwullems
 
java project.pptx
java project.pptxjava project.pptx
java project.pptxSwapnaRay6
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJamshid Hashimi
 
Fred Spencer & Blain Hamon: Advanced Titanium for iOS
Fred Spencer & Blain Hamon: Advanced Titanium for iOSFred Spencer & Blain Hamon: Advanced Titanium for iOS
Fred Spencer & Blain Hamon: Advanced Titanium for iOSAxway Appcelerator
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha Ocakçı
 
The Ruby Racer: under the hood
The Ruby Racer: under the hoodThe Ruby Racer: under the hood
The Ruby Racer: under the hoodcowboyd
 
NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05lrdesign
 
Interesting Facts About Javascript
Interesting Facts About JavascriptInteresting Facts About Javascript
Interesting Facts About JavascriptManish Jangir
 
Javascript for Intermediates
Javascript for IntermediatesJavascript for Intermediates
Javascript for IntermediatesAnkit Agrawal
 

Similaire à JavaScript Beyond jQuery (Jfokus 2013) (20)

Kevin Whinnery: Write Better JavaScript
Kevin Whinnery: Write Better JavaScriptKevin Whinnery: Write Better JavaScript
Kevin Whinnery: Write Better JavaScript
 
Write Better JavaScript
Write Better JavaScriptWrite Better JavaScript
Write Better JavaScript
 
Write Better JavaScript
Write Better JavaScriptWrite Better JavaScript
Write Better JavaScript
 
WDB005.1 - JavaScript for Java Developers (Lecture 1)
WDB005.1 - JavaScript for Java Developers (Lecture 1)WDB005.1 - JavaScript for Java Developers (Lecture 1)
WDB005.1 - JavaScript for Java Developers (Lecture 1)
 
Javascript omg!
Javascript omg!Javascript omg!
Javascript omg!
 
java project.pptx
java project.pptxjava project.pptx
java project.pptx
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Fred Spencer & Blain Hamon: Advanced Titanium for iOS
Fred Spencer & Blain Hamon: Advanced Titanium for iOSFred Spencer & Blain Hamon: Advanced Titanium for iOS
Fred Spencer & Blain Hamon: Advanced Titanium for iOS
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
The Ruby Racer: under the hood
The Ruby Racer: under the hoodThe Ruby Racer: under the hood
The Ruby Racer: under the hood
 
NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05
 
13243967
1324396713243967
13243967
 
Interesting Facts About Javascript
Interesting Facts About JavascriptInteresting Facts About Javascript
Interesting Facts About Javascript
 
Java basic
Java basicJava basic
Java basic
 
Huge web apps web expo 2013
Huge web apps web expo 2013Huge web apps web expo 2013
Huge web apps web expo 2013
 
Javascript Workshop
Javascript WorkshopJavascript Workshop
Javascript Workshop
 
Lecture7
Lecture7Lecture7
Lecture7
 
Javascript for Intermediates
Javascript for IntermediatesJavascript for Intermediates
Javascript for Intermediates
 
Java script
Java scriptJava script
Java script
 

Plus de johnwilander

Tre sårbarheter i webbappar
Tre sårbarheter i webbapparTre sårbarheter i webbappar
Tre sårbarheter i webbapparjohnwilander
 
Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5johnwilander
 
Hotlinking is Too Hot for Comfort
Hotlinking is Too Hot for ComfortHotlinking is Too Hot for Comfort
Hotlinking is Too Hot for Comfortjohnwilander
 
Stateless Anti-Csrf
Stateless Anti-CsrfStateless Anti-Csrf
Stateless Anti-Csrfjohnwilander
 
Advanced CSRF and Stateless Anti-CSRF
Advanced CSRF and Stateless Anti-CSRFAdvanced CSRF and Stateless Anti-CSRF
Advanced CSRF and Stateless Anti-CSRFjohnwilander
 
Application Security for Rich Internet Applicationss (Jfokus 2012)
Application Security for Rich Internet Applicationss (Jfokus 2012)Application Security for Rich Internet Applicationss (Jfokus 2012)
Application Security for Rich Internet Applicationss (Jfokus 2012)johnwilander
 
JavaScript för Javautvecklare
JavaScript för JavautvecklareJavaScript för Javautvecklare
JavaScript för Javautvecklarejohnwilander
 
Application Security, in Six Parts (HackPra 2012)
Application Security, in Six Parts (HackPra 2012)Application Security, in Six Parts (HackPra 2012)
Application Security, in Six Parts (HackPra 2012)johnwilander
 
RIPE: Runtime Intrusion Prevention Evaluator
RIPE: Runtime Intrusion Prevention EvaluatorRIPE: Runtime Intrusion Prevention Evaluator
RIPE: Runtime Intrusion Prevention Evaluatorjohnwilander
 
Application Security for RIAs
Application Security for RIAsApplication Security for RIAs
Application Security for RIAsjohnwilander
 

Plus de johnwilander (10)

Tre sårbarheter i webbappar
Tre sårbarheter i webbapparTre sårbarheter i webbappar
Tre sårbarheter i webbappar
 
Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5
 
Hotlinking is Too Hot for Comfort
Hotlinking is Too Hot for ComfortHotlinking is Too Hot for Comfort
Hotlinking is Too Hot for Comfort
 
Stateless Anti-Csrf
Stateless Anti-CsrfStateless Anti-Csrf
Stateless Anti-Csrf
 
Advanced CSRF and Stateless Anti-CSRF
Advanced CSRF and Stateless Anti-CSRFAdvanced CSRF and Stateless Anti-CSRF
Advanced CSRF and Stateless Anti-CSRF
 
Application Security for Rich Internet Applicationss (Jfokus 2012)
Application Security for Rich Internet Applicationss (Jfokus 2012)Application Security for Rich Internet Applicationss (Jfokus 2012)
Application Security for Rich Internet Applicationss (Jfokus 2012)
 
JavaScript för Javautvecklare
JavaScript för JavautvecklareJavaScript för Javautvecklare
JavaScript för Javautvecklare
 
Application Security, in Six Parts (HackPra 2012)
Application Security, in Six Parts (HackPra 2012)Application Security, in Six Parts (HackPra 2012)
Application Security, in Six Parts (HackPra 2012)
 
RIPE: Runtime Intrusion Prevention Evaluator
RIPE: Runtime Intrusion Prevention EvaluatorRIPE: Runtime Intrusion Prevention Evaluator
RIPE: Runtime Intrusion Prevention Evaluator
 
Application Security for RIAs
Application Security for RIAsApplication Security for RIAs
Application Security for RIAs
 

Dernier

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
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
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 

Dernier (20)

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
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
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
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
 

JavaScript Beyond jQuery (Jfokus 2013)

  • 1. JavaScript Beyond jQuery John Wilander @johnwilander
  • 3. Part 1: Typing @johnwilander
  • 4. Java Types Primitive: byte, short, int, long, float, double, boolean, char The rest is objects, so called reference types JavaScript Primitive: string, number, boolean, function, undefined The rest is object @johnwilander
  • 5. Java Types Primitive: byte, short, int, long, float, double, boolean, char JavaScript Primitive: string, number, boolean, function, undefined @johnwilander
  • 6. Java Types Primitive: byte, short, int, long, float, double, boolean, charnot Strings are general objects, they're a type JavaScript Primitive: string, number, boolean, function, undefined @johnwilander
  • 7. Java Types Primitive:Only one type byte, for numbers, i.e. long, float, double, short, int, no difference boolean, char between integers or decimals JavaScript Primitive: string, number, boolean, function, undefined @johnwilander
  • 8. Java Types Primitive: byte, short, int, long, float, double, boolean, char Functions are full objects with their own type JavaScript Primitive: string, number, boolean, function, undefined @johnwilander
  • 9. Java Types Primitive: byte, short, int, long, float, double, JavaScript's boolean, char version of uninitialized is JavaScript undefined Primitive: string, number, boolean, function, undefined @johnwilander
  • 10. Java Static vs Dynamic Typing Static typing: String name; Variables have types name = ”John”; Values have types name = 34; Variables cannot change type JavaScript Dynamic typing: var name; Variables have no types name = ”John”; Values have types name = 34; Variables change type dynamically @johnwilander
  • 11. Dynamic Typing JavaScript var name = ”John”; Variables have Values have types no types @johnwilander
  • 12. Strong vs Weak Typing @johnwilander
  • 13. Strong vs Weak Typing Strong !== good Weak !== bad @johnwilander
  • 14. Java Strong vs Weak Typing int intVar = 4; Pretty strong typing "" + intVar; Implicit type conversion intVar + 0.0; Implicit, widening type conv. intVar + (int)0.0; Explicit type conversion intVar + null; Not allowed JavaScript var dynVar = 4; Very weak typing dynVar + ""; Implicit type conversion dynVar + null; Implicit type conversion dynVar + []; Implicit type conversion dynVar + [0]; Implicit type conversion @johnwilander
  • 15. Type Safe ≈ no type errors at runtime @johnwilander
  • 16. John's Conclusion Java is a statically, strongly typed language with decent type safety JavaScript is a dynamically, weakly typed language with decent type safety @johnwilander
  • 17. Object Orientation @johnwilander
  • 18. Java: Classes & Objects Object Class Object Executing Source Object code Class Singleton @johnwilander
  • 19. JavaScript: Functions, Object & Prototypes Object Prototype Object Executing Source Object code Function Function @johnwilander
  • 20. JavaScript: Functions, Object & Prototypes Object Prototype Object Executing Source Object code Function Anonymous closures Function Modules @johnwilander
  • 21. Keywords in JavaScript Statistics from: jQuery jQuery.Mobile Prototype Ext JS MooTools Backbone Underscore http://ariya.ofilabs.com/2012/03/most-popular-javascript-keywords.html @johnwilander
  • 22. Keywords in JavaScript Functions, functions, functions Seldom new Almost never classes as types @johnwilander
  • 23. Java: Extension by Inheritance Subclass extends Super class @johnwilander
  • 24. Java: Subtyping by Inheritance Super type extends Subtype @johnwilander
  • 25. Through inheritance Java classes get larger in terms of functions and smaller in terms of type (more specific) @johnwilander
  • 26. In JavaScript extension and subtyping are separate things @johnwilander
  • 27. Why do we want to subtype? Because we think in terms of static typing and is-a-relations @johnwilander
  • 28. Static Typing and Subtyping Java public void doPurchase(Item item) Accepts Item or subtypes to Item @johnwilander
  • 29. Dynamic Typing JavaScript public void doPurchase(Item item) @johnwilander
  • 30. Dynamic Typing JavaScript public void doPurchase(Item item) @johnwilander
  • 31. Dynamic Typing JavaScript public void doPurchase(Item item) @johnwilander
  • 32. Dynamic Typing JavaScript public void doPurchase(Item item) @johnwilander
  • 33. Dynamic Typing JavaScript function doPurchase(item)__ Accepts anything ... or nothing @johnwilander
  • 34. Dynamic Typing JavaScript function doPurchase(item)__ Can return anything ... or nothing @johnwilander
  • 35. Part 2: To start a JavaScript program @johnwilander
  • 36. <html> JavaScript and Web <head> <script src=”js/main.js”></script> <script> var JW = {}; // More code </script> </head> <body> <button onclick="document.getElementById('field2').value= document.getElementById('field1').value">Copy text</button> <div> Some information </div> <script> JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script> </body> </html> @johnwilander
  • 37. JavaScript and Web <html> <head> Script from file in <head> <script src=”js/main.js”></script> Synchronous loading and <script> var JW = {}; execution // More code </script> </head> <body> <button onclick="document.getElementById('field2').value= document.getElementById('field1').value">Copy text</button> <div> Some information </div> <script> JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script> </body> </html> @johnwilander
  • 38. <html> JavaScript and Web <head> <script src=”js/main.js”></script> Inlined script in <head> <script> var JW = {}; Synchronous execution // More code </script> before DOM is loaded </head> <body> <button onclick="document.getElementById('field2').value= document.getElementById('field1').value">Copy text</button> <div> Some information </div> <script> JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script> </body> </html> @johnwilander
  • 39. <html> JavaScript and Web <head> <script src=”js/main.js”></script> <script> var JW = {}; // More code </script> Script directly in HTML, </head> <body> executed on click event <button onclick="document.getElementById('field2').value= document.getElementById('field1').value">Copy text</button> <div> Some information </div> <script> JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script> </body> </html> @johnwilander
  • 40. <html> JavaScript and Web <head> <script src=”js/main.js”></script> <script> var JW = {}; // More code </script> </head> <body> <button onclick="document.getElementById('field2').value= Inlined script in <body> document.getElementById('field1').value">Copy text</button> <div> Some information Executed when the </div> <script> parser gets here JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script> </body> </html> @johnwilander
  • 41. <html> JavaScript and Web <head> <script src=”js/main.js”></script> <script> var JW = {}; // More code </script> </head> <body> <button onclick="document.getElementById('field2').value= document.getElementById('field1').value">Copy text</button> <div> Some information Script from file in <body> </div> <script> Loaded and executed synchronously JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script> </body> </html> @johnwilander
  • 42. Good Practice: 1. All JavaScript on file. 2. All statically loaded JavaScript in one block. @johnwilander
  • 43. Dynamic Loading (function(){ var oldFirstScript = document.getElementsByTagName('script')[0]; newScript = document.createElement('script'), newScript.async = true; newScript.src = 'js/script.js'; oldFirstScript.parentNode.insertBefore( newScript, oldFirstScript); }()); @johnwilander
  • 44. OK, that's loading. But I want to start. @johnwilander
  • 45. Java In the Beginning public static void main(String[] args) JavaScript (function(){}()); window.someGlobalFunction(); @johnwilander
  • 46. Self-Invoking Functions Anonymous, self-invoking with parameter (function(me) { // Code }('John')); Anonymous, self-invoking without parameter (function() { // Code }()); @johnwilander
  • 47. Part 4: Variables @johnwilander
  • 48. JavaScript Scope var GLOB = {}; GLOB.func = function(array) { var local = …; … for (var i=0; i<array.length; i++){ … var temp = array[i]; } }; @johnwilander
  • 49. JavaScript Scope var GLOB = {}; GLOB.func = function(array) { var local = …, i, temp; … for (i=0; i<array.length; i++){ … temp = array[i]; } }; @johnwilander
  • 50. JavaScript Scope var GLOB = {}; GLOB.func = function(array) { var local = …, i, temp; … for (i=0; There are only two variable scopes: i<array.length; i++){ … Global or local function scope. temp = array[i]; } All local variables are hoisted to }; the top of the function. @johnwilander
  • 51. JavaScript Closure (function(array) { var i, temp; … for (i=0; i<array.length; i++){ … temp = array[i]; } }([1, 2, 3])); @johnwilander
  • 52. JavaScript Closure (function(array) { var i, temp; … for (i=0; i<array.length; i++){ … temp =Aarray[i]; its scope and its closure keeps } context during its life span. }([1, 2, 3])); A reference ending up inside the closure (array above) will keep its value inside the closure. @johnwilander
  • 53. JavaScript Closure Pitfall for(i=0; i<pages.length; i++) { var page = pages[i]; pageElement.load(page.url, function() { launchForm(page.form); }); } @johnwilander
  • 54. JavaScript Closure Pitfall for(i=0; i<pages.length; i++) { var page = pages[i]; pageElement.load(page.url, function() { launchForm(page.form); }); Callback function since } pageElement.load() is asynchronous @johnwilander
  • 55. JavaScript Closure Pitfall for(i=0; i<pages.length; i++) { var page = pages[i]; pageElement.load(page.url, function() { page is hoisted and thus gets launchForm(page.form); }); a new value for each iteration } @johnwilander
  • 56. JavaScript Closure Pitfall var page; for(i=0; i<pages.length; i++) { page = pages[i]; pageElement.load(page.url, page is hoisted and thus gets function() { launchForm(page.form);iteration a new value for each }); } @johnwilander
  • 57. JavaScript Closure Pitfall var page; for(i=0; i<pages.length; i++) { page = pages[i]; pageElement.load(page.url, function() { launchForm(page.form); }); When the callback is run page } will refer to pages[pages.length-1] or at least another value than intended. @johnwilander
  • 58. JavaScript Closure Pitfall var page; for(i=0; i<pages.length; i++) { page = pages[i]; pageElement.load(page.url, function() { launchForm(page.form); }); } @johnwilander
  • 59. Making Use of Closures JavaScript var page; for(i=0; i<pages.length; i++) { page = pages[i]; (function(page) { pageElement.load(page.url, function() { launchForm(page.form); } }); })(page); } @johnwilander
  • 60. Making Use of Closures JavaScript var page; for(i=0; i<pages.length; i++) { page = pages[i]; (function(page) { pageElement.load(page.url, function() { launchForm(page.form); } We bind page to a new closure }); })(page); so that the callback refers } correctly @johnwilander
  • 61. With self-invoking functions, scope, and closures we are ready for the most important design pattern: Part 5: The Crockford Module or Module Pattern @johnwilander
  • 62. JavaScript JW.cache = (function(){}()); @johnwilander
  • 63. JavaScript JW.cache = (function(){ return {}; }()); @johnwilander
  • 64. JavaScript JW.cache = (function(){ return { getPatient: function(personnummer) { } }; }()); @johnwilander
  • 65. JavaScript JW.cache = (function(){ var cache = {}; return { getPatient: function(personnummer) { } }; }()); @johnwilander
  • 66. JavaScript JW.cache = (function(){ var cache = {}; return { getPatient: function(personnummer) { var res=cache[personnummer]; // Check if fresh // Return } }; }()); @johnwilander
  • 67. JavaScript JW.cache = (function(){ var cache = {}; return { getPatient: function(personnummer) { var res=cache[personnummer]; if(_isValid(res)) { return res.patient; } else { // Handle cache miss } } }; }()); @johnwilander
  • 68. JavaScript JW.cache = (function(){ var cache = {}, _isValid = function(res) { } return { getPatient: function(personnummer) { var res=cache[personnummer]; if(_isValid(res)) { return res.patient; } else { // Handle cache miss } } @johnwilander
  • 69. JavaScript JW.cache = (function(){ var cache = {}, _isValid(res) { return !res ? false : (Date.now() - res.timestamp) <= 60000; // One minute } return { getPatient: function(personnummer) { var res=cache[personnummer]; if(_isValid(res)) { return res.patient; } else { // Handle cache miss @johnwilander
  • 70. JavaScript JW.cache = (function(){ var cache = {}, _isValid(res) { return !res ? false : (Date.now() - res.timestamp) <= 60000; // One minute } return { We can have (closure) private variables and functions getPatient: function(personnummer) { var res=cache[personnummer]; if(_isValid(res)) { return res.patient; } else { // Handle cache miss @johnwilander
  • 71. JavaScript Crockford = (function(initParam) { var privVar1, privVar2, _privFunc1 = function() { }, _privFunc2 = function() { }; return { pubVar1: ”value”, pubFunc1: function() { } }; }(initParam)); @johnwilander
  • 72. Part 6: Named Parameters @johnwilander
  • 73. Java Method Signatures public void execPurchase(int, String, String, boolean, User) JavaScript function execPurchase(price, item, discountCode, wantsSpam, user) @johnwilander
  • 74. Java Method Signatures builder = new Purchase.Builder(); Purchase purchase = builder.setPrice(9900) .setItem(”cap”).wantsSpam(false) .setUser(user).build(); JavaScript function execPurchase(purchase) { purchase.price … purchase.item … purchase.wantsSpam … purchase.user … @johnwilander
  • 75. Part 7: Asynchronous Module Definition (AMD) with require.js @johnwilander
  • 76. Concatenate and minify @johnwilander
  • 77. Concatenate and minify You may want to separate third party code to be able to cache it harder. @johnwilander
  • 78. Concatenate and minify The goal is to mimimize the number of HTTP requests and the size of data over the wire. @johnwilander
  • 79. Tools for Concatenation and Minification • Google Closure Compiler • UglifyJS • require.js Concatenates and minifies with Closure Compiler or UglifyJS @johnwilander
  • 80. require.js – import and namespace in JavaScript @johnwilander
  • 81. require([ "backbone", "underscore", "models/CartModel", "text!templates/CartItem.html"], function (Backbone, _, CartModel, cartItemTemplate) { // Code dependent on Backbone etc }); @johnwilander
  • 82. paths : { jquery : "vendor/jquery.min", backbone : "../components/backbone/backbone-min", underscore : "../components/underscore/underscore" } main.js require([ "backbone", "underscore", "models/CartModel", "text!templates/CartItem.html"], function (Backbone, _, CartModel, cartItemTemplate) { // Code dependent on Backbone etc }); @johnwilander
  • 83. File system, like Java packages require([ "backbone", "underscore", "models/CartModel", "text!templates/CartItem.html"], function (Backbone, _, CartModel, cartItemTemplate) { // Code dependent on Backbone etc }); @johnwilander
  • 84. require([ "backbone", Local name, like "underscore", dependency injection "models/CartModel", "text!templates/CartItem.html"], function (Backbone, _, CartModel, cartItemTemplate) { var model = new CartModel(); }); @johnwilander
  • 85. Define new modules define([ "backbone", "underscore", "models/CartModel", "text!templates/CartItem.html"], function (Backbone, _, CartModel, cartItemTemplate) { var CartItemView = …; … return CartItemView; }); @johnwilander
  • 86. CartItemView.js @johnwilander
  • 87. index.html without require.js or the like <head> <script src="js/lib/jquery-1.9.0.min.js"></script> <script src="js/lib/jquery-encoder-0.1.0.js"></script> <script src="js/base.js"></script> <script src="js/JW/util/util.js"></script> <script src="js/JW/personnummer/Personnummer.js"></script> <script src="js/JW/patient/Patient.js"></script> … <script src="js/JW/cache/cache.js"></script> <script src="js/JW/proxy/proxy.js"></script> <script src="js/JW/gui/gui.js"></script> </head> … manually, in the right order. @johnwilander
  • 88. index.html with require.js <head> <script data-main="scripts/main" src="scripts/require.js" > </script> </head> @johnwilander
  • 89. index.html with require.js <head> <script data-main="scripts/main" src="scripts/require.js" > </script> </head> require.config({ … paths : { jquery : "vendor/jquery.min", backbone : "../components/backbone/backbone-min", underscore : "../components/underscore/underscore" } }); require(["app"], function (App) { App.start(); }); main.js @johnwilander
  • 90. Reference Documentation Always developer.mozilla.org Never www.w3schools.com Why? w3fools.com @johnwilander
  • 91. The Stream http://javascriptweekly.com/ @javascript_news @BrendanEich @littlecalculist @addy_osmani @addyosmani @paul_irish @badass_js @rwaldron @slicknet @kangax @unscriptable @sthlmjs @johnwilander
  • 92. dojo-release-1.8.3.zip 11 Mb ext-4.1.1a-gpl.zip 45,7 Mb ext-all.js 1 Mb yui_3.8.1.zip 28,1 Mb @joakimkemeny & @johnwilander
  • 93. Simplified Dom api Templates & shims Widgets MVC @joakimkemeny & @johnwilander
  • 94. underscore Modernizr jQuery Simplified Dom api Templates & shims Widgets MVC @joakimkemeny & @johnwilander
  • 95. Handlebars Mustach Simplified Dom api Templates & shims Widgets MVC @joakimkemeny & @johnwilander
  • 96. Simplified Dom api Templates & shims Ember Backbone angular Widgets MVC @joakimkemeny & @johnwilander
  • 97. Simplified Dom api Templates & shims Widgets MVC Spine @joakimkemeny & @johnwilander
  • 98. Simplified Dom api Templates & shims Widgets MVC Bootstrap jQuery UI @joakimkemeny & @johnwilander
  • 99. Simplified Dom api Templates & shims Ext JS Dojo YUI Widgets MVC @joakimkemeny & @johnwilander
  • 100. All-in-one frameworks are best suited for newly written single-purpose applications without mashup behavior. @joakimkemeny & @johnwilander
  • 101. Micro frameworks are better if you need to integrate legacy code, some nifty CMS product, or if you have logic/content from third parties. Micro frameworks don't ”take over” you application. @joakimkemeny & @johnwilander