Advanced JS

Laurynas Veržukauskas

NFQ Akademija

Part 1

The Problem

  1. JavaScript sucks
  2. We need it

JavaScript sucks

  • lack of module system

  • weak-typing

  • late binding

  • finicky equality/automatic conversion

  • this behaviour

"lack of module definition"

 

 

 

Asynchronous Module Definition

requirejs.org

define([
    'jquery',
    'modernizr',
    'utils/proxy',
    'bootstrap/tooltip'
], function ($, Modernizr, proxy) {
    'use strict';

    function Tooltip() {
        if (Modernizr.ios) {
            return {
                create: function () {
                    return this;
                }
            };
        }
    }

    Tooltip.prototype.create = function (element, options) {
        // some code removed from here

        return this;
    };

    return new Tooltip();
});

"weak-typed"

 

 

CoffeeScript

TypeScript

Dart

class Animal
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5

class Horse extends Animal
  move: ->
    alert "Galloping..."
    super 45

sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"

sam.move()
tom.move(34)
class Animal {
    constructor(public name) { }
    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    move() {
        alert("Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python")
var tom: Animal = new Horse("Tommy the Palomino")

sam.move()
tom.move(34)

"late binding"

 

TL;DR:

  • bad performance*
  • run-time errors ("method not found", ...)
  • prevents static analysis (IDE features break)

 

 

"finicky equality

automatic conversion"

 

 

https://dorey.github.io/JavaScript-Equality-Table/unified/

 

 

"this behaviour"

 

var obj = {
    myMethod : function () {
        // this == window
    }
};
var myFun = obj.myMethod;
myFun();

//----------------------

function myFun() {
    // this == obj
}
var obj = {
    someData: "a string"
};
myFun.call(obj);

Part 2

Cool thingies

Feature Detection

.no-cssgradients .glossy {
    background: url("images/glossybutton.png");
}

.cssgradients .glossy {
    background-image: linear-gradient(top, #555, #333);
}

Workflow helpers

  • Gulp
  • Grunt

Automated tests

Selenium vs PhantomJS

Karma vs Casper

Templating

  • Handlebars
  • Hogan
  • ...

Data Binding

  • Rivets
  • Ractive
  • ...

Frameworks

  • Angular
  • Knockout
  • Ember
  • Backbone
  • ...

Advanced JS

By Laurynas Veržukauskas