You don't know JavaScript

Created by Aidas Klimas

About Me


var foo;
foo[' '] = 5
console.log(foo(6))
if (false) {
  function foo(undefined) {
    "use strict"
    a = 3
    return a * foo[' '] * undefined
    var a = b
  }
}

Closure


function foo() {
  var a = 2;
  function bar() {
      console.log( a );
  }
  return bar;
}
var baz = foo();
baz(); // 2 -- Whoa, closure was just observed, man.
          

What is the answer?


a = 2;
var a;
console.log(a);
      
console.log(a); -> 2

console.log(foo);
var foo;
function foo() {

}
var foo;
      

"use strict"


function foo() {
  "use strict";
  bar = 6;
}
foo();
      

ReferenceError: bar is not defined

Functions are objects


foo.a = 5;
function foo() {
  console.log(foo.a);
}
      

$('#foo');
$.each( ... );
      

Use semicolons!


$(function foo(){
  alert('a')
})

(function bar() {
  alert('b')
})()
          
TypeError: object is not a function

var foo;
foo[' '] = 5
console.log(foo(6)) // --> 90
if (false) {
  function foo(undefined) {
    "use strict"
    a = 3
    return a * foo[' '] * undefined
    var a = b
  }
}

var obj = {
  a: 2,
  foo: function () {
    console.log(this.a);
  }
};
obj.foo();// -> 2

var obj = {
  a: 2,
  foo: function () {
    console.log(this.a);
  }
};
var bar = obj.foo; // function reference/alias!
var a = "oops, global"; // `a` also property on global object
bar();// --> ?
bar(); // --> "oops, global" setTimeout(obj.foo, 100);

setTimeout(obj.foo, 100)

Solution nr. 1


setTimeout(function () {
  obj.foo()
}, 100);

Solution nr. 2


setTimeout(obj.foo.bind(obj), 100);

bind


function Foo(array) {
  this.count = 0;
  $.each(array, function () {
    this.count++;
  }.bind(this));
}

Module pattern


function fooModule() {
  var something = "cool "; // private variable
  function doSomething() {
    console.log(something);
  }
  function append(string) {
    return something += string;
  }
  return {
    doSomething: doSomething,
    append: append
  };
}
console.log(fooModule().append('Banana'));// -> "cool Banana"
var a = fooModule().append;
console.log(a('Apple'), a(' Orange'));// -> "cool Apple", "cool Apple Orange"

function composedModule() {
  var bar = "awesome"; // private variable
  var foo = fooModule();
  var append = foo.append;

  foo.append = function(string) {
    return append(string) + ' ' + bar;
  };

  foo.upper = function(string) {
    return foo.append(string).toUpperCase();
  };
  return foo;
}
var module = composedModule()
console.log(module.append('Banana'));// -> "cool Banana awesome"
console.log(module.upper('nana'));// -> "COOL BANANANANA AWESOME"

You Don't Know JS

https://github.com/getify/You-Dont-Know-JS

Thank You!

Questions?

Get slides from klimas.lt/slides