Reference

ECMA:

IMPLEMENTATION:

Base App Template

var APP = APP || (function($) {
    var Utils   = {}, // Your Toolbox
        Ajax    = {}, // Your Ajax Wrapper
        Events  = {}, // Event-based Actions
        Routes  = {}, // Your Page Specific Logic
        App     = {}, // Your Global Logic and Initializer
        Public  = {}; // Your Public Functions
    return Public;
})(window.jQuery);
 
jQuery(document).ready(APP.init);

multiline strings:

var Templates = {
     multilineString: '<div class="pp_pic_holder"> \
      <div class="ppt">&nbsp;</div> \
      <div class="pp_top"> \
      <div class="pp_left"></div>';
};

logging:

if (typeof window.console == "undefined") {
    window.console = {
        log: function(){},
        debug: function(){},
        trace: function(){}
    };
}

types and casts

// cast of 1 or 0 to bool
var bool = !!num;

Error Handling

http://eloquentjavascript.net/chapter5.html throw exceptions for exceptional things and not for expected things

EvalError Error in the eval() function
RangeError Out of range number value
ReferenceError illegal reference
SyntaxError A syntax error inside the eval(), All other syntax errors are not caught by try/catch/finally, and will trigger the default browser error message, use the onerror event
TypeError Error in the expected variable type .
URIError Error when encoding or decoding the URI (ie: when calling encodeURI()).
// new error condition
var myError = new Error(100, "My user defined error text")
try {
    throw myError;
    // throw RangeError;
} catch(e) {
    alert(e.message + e.code + e.name);
    // if (e instanceof TypeError)
    // else if (e instanceof RangeError)
    // if (e.name.toString() == "TypeError")
} finally {
    alert("Sorted");
}

Call and Apply

The apply() method is a variation on the call() method: The apply() method lets you pass the parameters from one method to the other in array arguments, The call() method requires the full list of parameters:

exterior.call(this, extColor, doorCount, airWing, tireWidth); The apply() method, on the other hand, lets you specify arguments on its second parameter:

exterior.apply(this, arguments);

// funzione di esempio
var friendlyGreet = function(somebody) {
    alert("Hi, " + somebody.name + ", I'm " + this.name);
};
 
//The friendlyGreet function takes a single parameter, the person being greeted. Here are examples of Bob and //Alice greeting each other using call():
friendlyGreet.call(Bob, Alice); // alerts "Hi, Alice, I'm Bob"
friendlyGreet.call(Alice, Bob); // alerts "Hi, Bob, I'm Alice"
 
//And here are the same examples using apply():
friendlyGreet.apply(Bob, [ Alice ]); // alerts "Hi, Alice, I'm Bob"
friendlyGreet.apply(Alice, [ Bob ]); // alerts "Hi, Bob, I'm Alice"

Bind

var x = 9;
var module = {
  x: 81,
  getX: function() { return this.x; }
};
 
module.getX(); // 81
 
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
 
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81

Call

function Product(name, price) {
    this.name = name;
    this.price = price;
 
    if (price < 0){
        throw RangeError('Cannot create product "' + name + '" with a negative price');
    }
    return this;
}
 
function Food(name, price) {
    Product.call(this, name, price);
}

Apply

var module = {
    util: function(arg1, arg2){
        console.log(this.var);
    }
};
var caller_module = {
    test: function(){
        module.util.apply(this, [arg1, agr2]);
    }
};

let - variable scope

local variables

problem code:

var funcs = [];
for (var i = 0; i < 3; i++) {          // loop
    on_click( function() {            // and store them in funcs
        console.log("value: " + i); // each should log its value.
    } );
}
// and now let's run each one to see

timers

var timer = window.setTimeout(function(params){
    console.log(params);
}, 500, params);
window.clearTimeout(timer);
var alarm = {
    remind: function(aMessage) {
        alert(aMessage);
        delete this.timeoutID;
    },
    setup: function() {
        this.cancel();
        var self = this;
        this.timeoutID = window.setTimeout(function(msg) {
            self.remind(msg);
        }, 1000, "Wake up!");
    },
    cancel: function() {
        if(typeof this.timeoutID == "number") {
            window.clearTimeout(this.timeoutID);
            delete this.timeoutID;
        }
    }
};
window.onclick = function() { alarm.setup() };
var intervalID = window.setInterval(function(){}, 500);
clearInterval(intervalID);

RegExp

var regex = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(regex, "$2, $1");
 
var text = "First line"."\n"."second line";
var regex = /(\S+) line\n?/y;
var matches = regex.exec(text);// prints "First"

Array Cloning

nelle funzioni i valori scalari sono passati by value, ma gli oggetti e gli array vengono passati by reference!

var clone = myArray.slice(0);

Arguments

pseudo array

var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);

argomenti variabili:

// Math.max(1,2,3,4,3,2,1) == 4
function max() {
    var maxValue = 0;
    for ( var i=0; i<arguments.length; i++ ) {
        if ( arguments[i] > maxValue ) maxValue = arguments[i];
    }
    return maxValue;
}

dependency injection

// dependency injection of GLOBALS
(function(GLOBALS) {
        // use GLOBALS
}).call(this);
 
// dependency injection of foo and bar
var baz = (function(foo, bar) {
        return foo * bar;
})(10, 2);
// baz will equal 20