Javascript

General topics about Javascript and front-end develpoment.

Bower

Front-end package management tool.

Objects

Prototype

function Dog (breed) {
  this.breed = breed;
};

var buddy = new Dog("golden Retriever");

// add a method to prototype of Dog
Dog.prototype.bark = function() {
  console.log("Woof");
};

Inheritance by Prototype

Douglas Crockford's video course: Prototypal Inheritance

function Gizmo(id) {
    this.id = id;
}

Gizmo.prototype.toString = function() {
    return "gizmo " + this.id;
}
var g = new Gizmo(1);

Object

Javascript: The Good Parts

convert strings to numbers

    +"42" -> 42;
    Number("42") -> 42;
    parseInt("42", 10) -> 42;

truesy and falsey

functions

    // function expression
    var foo = funcion() {};

    // function statement
    function foo() {};

    // function statement is a short-hand for var statement, which will expand to:
    var foo = undefined;
    foo = function() {};

don't put function statement in a block, such as if block, since the function name will also be hoisted

style guides

Module Systems

https://www.airpair.com/javascript/posts/the-mind-boggling-universe-of-javascript-modules

AMD (Asynchronous Module Design)

asynchronous, unblocking

// this is an AMD module
define(function () {
    return something
})

CommonJS (CJS)

synchronous, blocking, easier to understand

// and this is CommonJS
module.exports = something

ES6

example, animal.js:

var foo = function() {};    //private

export function bark() {    //public
    console.log('bark');
}

app.js:

import {bark} as animal from './animal'
animal.bark();

tricks

deboucing an event

http://stackoverflow.com/questions/5489946/jquery-how-to-wait-for-the-end-of-resize-event-and-only-then-perform-an-ac

in the following code, the updateLayout function will only run after the resize event stopped 250ms

    // debounce the resize event
    $(window).on('resize', function() {
        clearTimeout(window.resizedFinished);
        window.resizedFinished = setTimeout(function(){
            updateLayout();
        }, 250);
    });