Brief notes about JS

El pasado miércoles un par de amigos se acercaron a hablar de típicos pain points de Javascript, os dejo las notas que tomamos. No pretende ser una guía de estilos (que hay unas cuantas en la red). Si detectáis algún error o discrepáis, comentad!

Brief notes about JS

Idiomatic JS

Useful constructions

For example:

    (function module_pattern_revealed() {

        var private_element = 2;

        function example_function() {
            operate_with_private_element
        }

        return {
            example_function: example_function
        }

    })();

This…

We have 4 ways of invoking a function:

    var myObject = {
        value: 0,
        increment: function (inc) {
            this.value += typeof inc === 'number' ? inc : 1;
        }
    };

    myObject.increment();  // 1
    myObject.increment(2); // 3

    myObject.double = function () {
        var that = this; // Workaround.
        var helper = function () {
            that.value = add(that.value, that.value);
        };
        helper(); // Invoke helper as a function.
    };

    // Invoke double as a method.
    myObject.double( );

helper is invoked as a function and this refers to the global scope. The usual workaround is use a variable called that or self that “caches” the value of this.


    var Quo = function (string) {
        this.status = string;
    };

    Quo.prototype.get_status = function () {
        return this.status;
    };

    // Make an instance of Quo.
    var myQuo = new Quo("value");
    myQuo.get_status() // value

The only strange behaviour is calling a function with a function invocation (constructor and method works fine).

The bad case is more common as it seems, because event handlers, DOM events, timeouts or other corner cases.

The solutions are:

  1. Understand why this behaves this way and react accordingly.
  2. Program only using properties, constructors (without forgetting new) or use apply (and derivates).
  3. Create variables like that.
  4. Don’t use this ever.

References

  1. Examples from Javascript: The Good Parts