Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Du JavaScript propre

Du JavaScript propre

Compilation personnelle de quelques bonnes pratiques de codage en JavaScript.

zenigata

June 13, 2013
Tweet

More Decks by zenigata

Other Decks in Programming

Transcript

  1. Inline <div style="width: 800px; margin: 1em auto; font: bold 1em/1.2

    Verdana, Arial, Helvetica, sans-serif"> <div style="float: left; width: 400px; padding: 1em 2em; font- size: 0.9em"> <span id="get-shit" onclick="callSomeFunction()">News</span> </div> </div>
  2. Point-virgule, où es-tu ? var foo = function() { }

    // parse error, semicolon expected test()
  3. Espace de nommage pollué // global scope var foo =

    42; function test() { // local scope foo = 21; } test(); foo; // 21
  4. Eval c'est le mal var foo = 1; function test()

    { var foo = 2; var bar = eval; bar('foo = 3'); return foo; } test(); // 2 foo; // 3
  5. QUnit test("prettydate.format", function() { function date(then, expected) { equal(prettyDate.format("2008/01/28 22:25:00",

    then), expected); } date("2008/01/28 22:24:30", "just now"); date("2008/01/28 22:23:30", "1 minute ago"); date("2008/01/28 21:23:30", "1 hour ago"); date("2008/01/27 22:23:30", "Yesterday"); date("2008/01/26 22:23:30", "2 days ago"); date("2007/01/26 22:23:30", undefined); });
  6. Mocha test('display received results', function () { var sr =

    new SearchResults(ul); sr.setResults(data); assert.equal(ul.find('.no-results').length, 0); assert.equal(ul.find('li.result').length, data.length); assert.equal( ul.find('li.result').first().attr('data-name'), data[0].name ); });
  7. Module var counter = (function() { var privateValue = 0;

    var publicMethod = function() { privateValue++; return privateValue; }; return { increment: publicMethod }; })(); // On passe à l'utilisation du compteur : counter.increment(); // 1 counter.privateValue; // undefined counter.privateValue = 0; counter.increment(); // 2
  8. Classe // A car "class" function Car( model ) {

    this.model = model; this.color = "silver"; this.year = "2012"; this.getInfo = function () { return this.model + " " + this.year; }; } var myCar = new Car("ford"); myCar.year = "2010"; console.log( myCar.getInfo() );
  9. Package var myapp = { subpackage: { counter: (function() {

    // ... })() } } // Et son utilisation : myapp.subpackage.counter.increment(); // 1