JavaScript, Beyond the Curly Braces

Loading...

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

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    Notes on slide 1

    In trivia we will give an abridged version of JS history and where it stands todayDrive by shooting: just to make sure we mention the basic data types we deal with all the time. The one item that can be surprisingly different and longer than you might expect are the functions. We will spend a little bit of time talking about them.As the title of the presentation suggests, it can be easy to look at JS syntax and its name and try to map everything else to C#, Java, C, etc. We will see that this is a big mistake and we will point out very important differences.In idiomatic JS we will see what proficient JS looks likeWe will take some time to explain how object creation and inheritance works in JS. If you haven’t read about it before it might just be completely different from anything you saw.JS lives in a very hostile environment. In coding conventions and pitfalls we will learn tidbits of advice that can spare you from a lot of grief.Finally, all the above has just been preparation to really get to the more practical goal. Understanding jQuery and using it to write less and better JS code. We will see that jQuery has good documentation but it can be hard to read if you’re not up to speed with some of the previous topics. Event the jQuery source code is very readable once you get comfortable with idiomatic JS.

    In trivia we will give an abridged version of JS history and where it stands todayDrive by shooting: just to make sure we mention the basic data types we deal with all the time. The one item that can be surprisingly different and longer than you might expect are the functions. We will spend a little bit of time talking about them.As the title of the presentation suggests, it can be easy to look at JS syntax and its name and try to map everything else to C#, Java, C, etc. We will see that this is a big mistake and we will point out very important differences.In idiomatic JS we will see what proficient JS looks likeWe will take some time to explain how object creation and inheritance works in JS. If you haven’t read about it before it might just be completely different from anything you saw.JS lives in a very hostile environment. In coding conventions and pitfalls we will learn tidbits of advice that can spare you from a lot of grief.Finally, all the above has just been preparation to really get to the more practical goal. Understanding jQuery and using it to write less and better JS code. We will see that jQuery has good documentation but it can be hard to read if you’re not up to speed with some of the previous topics. Event the jQuery source code is very readable once you get comfortable with idiomatic JS.

    2 Favorites

    JavaScript, Beyond the Curly Braces - Presentation Transcript

    1. Beyond the Curly Braces
      Advanced JavaScript
      Sergio Pereira
      WI.NET Users Group – July 14th2009
    2. WHOIS
      About Sergio
      sergio@sergiopereira.com
      http://sergiopereira.com/blog
      @sergiopereira
      http://chicagoalt.net
    3. agenda
    4. Advanced javascript
    5. Advanced javascript
      BUT FIRST THE BASICS
    6. Advanced javascript
      Once upon a time…
      • 1995: Mocha, LiveScript, JavaScript (Netscape)
      • 1995: NS Navigator 2.0 (Java + JavaScript)
      • 1995: Confusion started
      • 1996: MS IE 3.0 calls it JScript (not quite the same)
      • 1997: ECMA-262, ECMAScript
    7. Advanced javascript
      World's Most Misunderstood Language
      • The Name
      • Mispositioning
      • Design Errors
      • Bad Implementations
      • The Browser
      • Bad Books
      • Substandard Standard
      • JavaScript is a Functional Language
    8. Advanced javascript
      But The Truth Is
      • JavaScript is not a toy
      • Solves real problems as a real language
      • Quite fancy sometimes
      • Not freaking Java (or C#), OK?
    9. Advanced javascript
      JavaScript in a Snapshot
      • Dynamic
      • Objects: glorified containers
      • Prototypal inheritance
      • Textual delivery
      • Lambdas
      • Global variables tie it all
    10. Advanced Javascript
      Data Types
      Primitive Types (value types)
      String
      Number
      Boolean
      (true, false)
      Undefined
      (undefined)
      Null
      (null)
      Objects (reference types)
      Object
      Array
      Date
      Boolean
      Errors…
      Math
      Reg. Expression
      (RegExp)
      Function
      Number
      String
      Global
    11. Advanced Javascript
      Undefined
      (undefined)
      Null
      (null)
      Default value for variables, parameters,
      and missing object properties
      var name = "Homer";
      varhairColor = null;
      var city = "Springfield";
      var state;
    12. Advanced Javascript
      Number
      (IEEE-754, 64-bit, Double)
      Boolean
      (true, false)
      //integer literals
      varage = 26;
      vartemperature = -8;
      varpermission = 0775; //=509
      varflags = 0x1c; //=28
      //Double prec. literals
      varheight = 6.15;
      varfactor = 5.73e-1; //=.573
      //NaN
      varwhat = "x"/3; //= NaN
      varfirstTime = true;
      varfound = false;
      String
      varfirstName = "Selma";
      varlastName = 'Bouvier';
    13. Advanced Javascript
      Array
      varnames = new Array();
      names[0] = 'Steve';
      names[1] = 'Chuck';
      names[names.length] = 'Jeff';
      names.push('Jason');
      varnames = [ ];
      //repeat as above…
      //or, preferred
      varnames = ['Steve', 'Chuck',
      'Jeff', 'Jason'];
    14. Advanced Javascript
      Date
      vartoday = new Date();
      //milliseconds since 1/1/1970
      vard = new Date(1234);
      //explicit
      var xmas = new Date(2008, 11, 25);
      //parsing, locale-dependent, avoid
      var xmas = new Date(Date.parse('12/25/2008'));
    15. Advanced Javascript
      RegExp
      varpatt1 = new RegExp('\d{2}$');
      varpatt2 = /d{2}$/;
      varpatt3 = new RegExp('\d{2}$', 'gi');
      varpatt4 = /d{2}$/gi;
      alert(patt1.test('abc78')); //  true
      '12a78'.replace(/d{2}$/, 'XYZ'); // '12aXYZ'
      'a1b2c7d8e'.split(/d/); // ['a','b','c','d','e']
    16. Advanced Javascript
      Function
      //normal declaration
      function play(chord) {
      alert('playing ' + chord);
      }
      //normal invocation
      play('Cm'); //  'playing Cm'
    17. Advanced Javascript
      Function
      //functions are data as well
      function f1() {
      alert('inside f1');
      }
      var f2 = f1;
      function run( someFunc ){
      someFunc();
      }
      run( f2 ); //  'inside f1'
    18. Advanced Javascript
      Function
      //functions are data as well
      function f1() {
      alert('inside f1');
      }
      var f2 = f1;
      function run( someFunc ){
      someFunc();
      }
      run( f2 ); //  'inside f1'
    19. Advanced Javascript
      Function
      //functions don't need a name
      function run( someFunc ){
      someFunc();
      }
      run(function () {
      alert('inside function');
      }); //  'inside function'
    20. Advanced Javascript
      Function
      //functions don't need a name
      function run( someFunc ){
      someFunc();
      }
      run( function () {
      alert('inside function');
      }
      ); //  'inside function'
    21. Advanced Javascript
      Function
      //parameter lists are optional
      function concat(){
      var res = '';
      for (var i=0; i<arguments.length; i++) {
      res += arguments[i];
      }
      return res;
      }
      alert( concat(123, 'abc', [7, 8, 9]) );
      //  '123abc7,8,9'
    22. Advanced Javascript
      Function
      //can be nested
      function prettyPrint(value, currency, rate){
      function formatCurr(num) {
      returnnum + ' ' + currency;
      }
      function convert() {
      return rate * value;
      }
      var converted = convert(value);
      var text = formatCurr(converted);
      alert(text);
      }
      prettyPrint(10.5, 'EUR', 0.797); //  8.3685 EUR
    23. Advanced Javascript
      Function
      //single-use, pinned functions
      (function (someParameter){
      //do something
      // …
      })(someArgument);
      Invocation!
    24. Advanced Javascript
      Invocation and the problem with this
      function func(arg1, arg2){
      return [this, arg1, arg2];
      }
      func(123, 456); //  [window, 123, 456]
      var car = new Object();
      car.start = func;
      car.start('now', 9); //  [car, 'now', 9]
      func.apply(car, ['p1', 'p2']);//  [car, 'p1', 'p2']
      func.call(car, 'p1', 'p2'); //  [car, 'p1', 'p2']
    25. Advanced Javascript
      Inner functions and this
      function calculateTotal(){
      function getTax(){
      return this.price * this.tax;
      }
      returnthis.price + getTax() +
      this.shippingCost;
      }
      var order = new Object();
      order.price = 10.25;
      order.tax = 0.07;
      order.shippingCost = 5;
      order.getTotal = calculateTotal;
      order.getTotal();
    26. Advanced Javascript
      Inner functions and this (the fix)
      function calculateTotal(){
      var that = this; //  very common
      function getTax(){
      return that.price * that.tax;
      }
      returnthis.price + getTax() +
      this.shippingCost;
      }
      var order = new Object();
      order.price = 10.25;
      order.tax = 0.07;
      order.shippingCost = 5;
      order.getTotal = calculateTotal;
      order.getTotal();
    27. Advanced Javascript
      Closures
      function createFuncArray() {
      var funcs = [ ];
      for (var n=0; n<10; n++) {
      funcs[n] = function () {
      alert('The number is ' + n);
      };
      }
      return funcs;
      }
      var allFunctions = createFuncArray();
      var show = allFunctions[6];
      show();//  Can you guess?
    28. Advanced javascript
      Other Function-related gotchas
      • Variables are scoped by function, not block.
      • No overloading, last one wins. Use default values.
      • arguments and this not passed to inner functions.
    29. Advanced Javascript
      Object
      //Explicit assembly
      varguitar = new Object();
      guitar.stringCount = 6;
      guitar.make = 'Gibson';
      guitar.model = 'Les Paul';
      alert(guitar.make); //  'Gibson'
    30. Advanced Javascript
      Object
      //factory function
      functioncreateGuitar(strings, make, model){
      var guitar = new Object();
      guitar.stringCount = strings;
      guitar.make = make;
      guitar.model = model;
      return guitar;
      }
      var g = createGuitar(6, 'Gibson', 'Les Paul');
      alert(g.make); //  'Gibson'
    31. Advanced Javascript
      Object
      //Object literal notation
      var emptyObject = {};
      var guitar = {
      stringCount: 6,
      make: 'Gibson',
      model: 'Les Paul'
      }; //  don't forget the ';'
      //or
      var guitar = {
      'stringCount': 6,
      'make': 'Gibson',
      'model': 'Les Paul'
      };
    32. Advanced Javascript
      Object
      //notation for methods
      var guitar = {
      stringCount: 6,
      make: 'Gibson',
      model: 'Les Paul',
      play: function (chord) {
      alert(chord + ' from a ' + this.model);
      }
      };
      guitar.play('C#'); //  'C# from a Les Paul'
    33. Advanced Javascript
      Object
      Wait, was that JSON? Not exactly.
      //JSON (see http://www.json.org/ )
      var guitarJson = "{ " +
      " 'stringCount': 6, " +
      " 'make': 'Gibson'," +
      " 'colors': [ 'black', 'white', 'red']," +
      " 'model': 'Les Paul'" +
      "} ";
      JSON is basically a collection of name:value pairs.
      - name is a string literal
      - value can be: a string, a number, null, true, false,
      an array, or another JSON object literal.
    34. Advanced Javascript
      Object
      //constructor function
      functionGuitar(strings, make, model){
      this.stringCount = strings;
      this.make = make;
      this.model = model;
      this.play = function (chord) {
      alert(chord + ' from a ' + this.model);
      };
      }
      var g = new Guitar(6, 'Gibson', 'Les Paul');
      g.play('C#'); //  'C# from a Les Paul'
    35. Advanced Javascript
      Member access notations
      //good 'ole dot notation
      guitar.model = 'Gibson';
      var p = guitar.price;
      //indexer notation
      guitar['model'] = 'Gibson';
      guitar['play']('C#');
    36. Advanced javascript
      What about document, window, etc?
      • Not JavaScript.
      • Part of the DOM.
      • Provided by the hosting environment.
      • Like the DTE in VS macros and other objects in Office automation.
    37. Advanced javascript
      What about XMLHttpRequest (xhr) ?
      • Not JavaScript.
      • Not even part of the DOM.
      • Provided by the hosting environment.
    38. Advanced javascript
      Identifiers
      • Start with a letter, _ or $ followed by more of these and numbers.
      • Convention: start variables and functions with lower case.
      • Convention: start constructors with upper case.
      • Avoid starting with _ or $
    39. Advanced javascript
      Reserved Words
      abstract boolean break byte case catch char class
      const continue debugger default delete do double
      else enum export extends false final finally float
      for function goto if implements import in
      instanceof int interface long native new null
      package private protected public return short
      static super switch synchronized this throw throws
      transient true try typeof var volatile void
      while with
      // Bug in the language
      driversLicense.class = 'B'; //  invalid!
      driversLicense['class'] = 'B'; //  huzzah!
    40. Advanced Javascript
      Inheritance in JavaScript
      • No classes.
      • Prototypal inheritance.
      • Inheritance through linkage.
      • Objects inherit directly from other objects.
    41. Advanced Javascript
      Inheritance in JavaScript
      generic
      var generic =
      { make: 'none', price :0 };
      var guitar = object( generic );
      guitar.model = 'Les Paul';
      guitar.price = 1200;
      guitar
      alert(guitar.model);
      //  Les Paul
      alert(guitar.price);
      //  1200
      alert(guitar.make);
      //  none
    42. Advanced Javascript
      Inheritance in JavaScript
      generic
      var generic =
      { make: 'none', price :0 };
      var guitar = object( generic );
      guitar.model = 'Les Paul';
      guitar.price = 1200;
      guitar
      generic.year = 2001;
      generic.model = 'n/a';
      alert(guitar.model);
      //  Les Paul
      alert(guitar.year);
      //  2001
    43. Advanced Javascript
      Inheritance in JavaScript
      Every object inherits from Object.prototype
      var obj = new Object();
      //same as
      var obj = object( Object.prototype );
      var d = new Date(1000);
      //behind the scenes:
      var newObj = object( Date.prototype );
      d = Date.apply( newObj, [1000] );
      if (d == null ) d = newObj;
    44. Advanced Javascript
      Inheritance in JavaScript
      Our constructors also have a prototype
      functionGuitar(strings, make, model){
      this.stringCount = strings;
      this.make = make;
      this.model = model;
      }
      Guitar.prototype.play = function (chord) {
      alert(chord + ' from a ' + this.model);
      };
    45. Advanced Javascript
      Inheritance in JavaScript
      Object.prototype
      Guitar.prototype
      myGuitarInstance
    46. Advanced Javascript
      Inheritance in JavaScript
      Oldest trick in JavaScript inheritance
      String.prototype.trim = function () {
      return this.replace(
      /^s*(S*(s+S+)*)s*$/,
      "$1");
      };
      var text = ' some user-entered value ';
      alert(text); //  'some user-entered value'
    47. Advanced Javascript
      I lied
      There's no object() function in Javascript.
      But let me give you one.
      function object(o) {
      function F() {}
      F.prototype = o;
      returnnew F();
      }
    48. Advanced Javascript
      JavaScript Idioms: Truthy & Falsy
      //Falsy values
      var f[1]= false;// D'oh!
      var f[2] = null;
      var f[3] = undefined;
      var f[4] = 0;
      var f[5] = "";
      var f[6] = NaN;
      if( f[X] ){
      // never gets here
      }
      //Truthy values
      var t[1] = true;
      var t[2] = new Object();
      var t[3] = "1";
      var t[4] = "0"; //  !!
      var t[5] = "false";//  !!
      if( t[X] ){
      // gets here always
      }
    49. Advanced Javascript
      JavaScript Idioms: || Default operator
      //returns the first Truthy or last operand.
      //e.g.: overriding missing arguments
      var sortOrder;
      if (arg) {
      sortOrder = arg;
      } else {
      sortOrder = 'Name ASC';
      }
      //same as
      var sortOrder = arg || 'Name ASC';
    50. Advanced Javascript
      JavaScript Idioms: && Guard operator
      //returns the first Falsy or last operand.
      // e.g.: avoiding null reference errors
      var obj2;
      if (obj1) {
      obj2 = obj1.prop;
      } else {
      obj2 = obj1;
      }
      //same as
      var obj2 = obj1 && obj1.prop;
    51. Advanced Javascript
      JavaScript Idioms: === and !==
      if (0 == "") {
      alert('Hey, I did not expect to see this.');//displayed
      }
      if (0 === "") {
      alert('This will not be displayed.');//not displayed
      }
      if (1 != true) {
      alert('Hey, I expected to see this.'); //not displayed
      }
      if (1 !== true) {
      alert('This will be displayed.');//displayed
      }
    52. Advanced Javascript
      JavaScript Idioms: Namespaces
      var ACME = {
      version: '7.1',
      formatCurrency: function(num){ /* … */ },
      //…
      };
      ACME.Ajax = {
      ajaxifyForm: function(formId){ /* … */ },
      showError: function(){ /* … */ },
      //…
      };
      ACME.Ajax.ajaxifyForm('myForm');
    53. Advanced javascript
      Coding convention:
      Always use curly braces
      if (something)
      doSomething();
      doSomethingElse();
      if (something){
      doSomething();
      }
      doSomethingElse();
    54. Advanced javascript
      Coding convention:
      Always end lines with punctuation
      return
      tax + shipping + price;
      var amount = tax
      + shipping
      + price;
      var amount = tax +
      shipping +
      price;
      Parsed as
      return;
      tax + shipping + price;
      return tax +
      shipping + price;
    55. Advanced javascript
      Coding convention:
      Globals
      • Avoid them.
      • Tend to clobber each other.
      • Namespaces are OK.
      • Name them with ALL_CAPS
    56. Advanced javascript
      Coding convention:
      eval()is evil
      var p = eval('obj.' + propertyName);
      var p = obj[ propertyName];
      //hidden evals
      setTimeout("alert('Time is up!');", 9000);
      setTimeout( function () {alert('Time is up');}, 9000);
      var func = new Function('p1', 'p2', 'return p1+p2;');
    57. Advanced javascript
      Coding convention:
      Declare variables at the top of function
      function f1(){
      var a, b, c;
      a = getA();
      if (a) {
      b = calcB(a);
      } else {
      c = getC();
      b = calcB(c);
      }
      }
    58. Advanced javascript
      Coding convention:
      Do not use assignments as expressions
      if ( flag = getFlag() ) {
      alert(flag);
      }
      //prefer:
      var flag = getFlag();
      if (flag) {
      alert(flag);
      }
    59. Questions ?
    60. Reference
      • JavaScript: The Good Parts by Douglas Crockford.
      • JavaScript: The Definitive Guide by David Flanagan.
      • Videos: Search for Douglas Crockford.
      • Shameless plug: my blog, JavaScript category.
      sergio@sergiopereira.com
      http://sergiopereira.com/blog
      @sergiopereira
      http://chicagoalt.net

    + Chicago ALT.NETChicago ALT.NET, 4 months ago

    custom

    605 views, 2 favs, 4 embeds more stats

    Presentation done for the WI.NET Users Group in Mil more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 605
      • 464 on SlideShare
      • 141 from embeds
    • Comments 0
    • Favorites 2
    • Downloads 0
    Most viewed embeds
    • 128 views on http://devlicio.us
    • 10 views on http://devlicious.com
    • 2 views on http://74.125.65.132
    • 1 views on http://feeds2.feedburner.com

    more

    All embeds
    • 128 views on http://devlicio.us
    • 10 views on http://devlicious.com
    • 2 views on http://74.125.65.132
    • 1 views on http://feeds2.feedburner.com

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

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

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

    Categories