W hat an E xtremely I nteresting and R eally D ifferent

javascript

What's gonna happen then?

  • Javascript is ! Java script (~5 min)
  • Javascript D-E-F (~ 50 min)
  • Javascript quick quiz (~15 min)

! java script

  • javascript vs. java
  • javascript vs. ECMAscript
  • javascript vs. ActionScript, as3 (whatever)
  • javascript vs. JS

JS is not everywhere

  • in browser: user interaction, animation, ria ..
  • as a server: web-server, static file serve ..
  • as autobot: building (grulp, grunt, less, sass ..), testing (Selenium, PhantomJS ..), etc.
  • as CLI app ..
  • ..

Dive into D-E-F

Before you begin, make sure you're comfortable with Javascript ABC, or just feel free to take tour from w3schools

Monday D-E-F

DOM is listening to event ..

Bubbling ↑ ↑ ↑

playground/bubbling.html
            
<div class="great-grand-father">
  <div class="grand-father">
    <div class="father">
      <div class="son"></div>
    </div>
  </div>
</div>
            
          
            
$('.son').on('click', function(event) {
  console.log('This is son', event.target);
});

$('.father').on('click', function(event) {
  console.log('This is father', event.target);
});

$('.grand-father').on('click', function(event) {
  event.stopPropagation(); // this will stop the click event to go up
  console.log('This is grand father', event.target);
});

$('.great-grand-father').on('click', function(event) {
  console.log('This is great grand father', event.target);
});

            
          

$.fn.live vs $.fn.bind

playground/live-bind.html
            
<body>
  <button>Clickable</button>
</body>
            
          
            
// Bind click listener by
//   $('button').bind('click', ...)
$('button').on('click', function() {
  console.log('Click from `on`');
});

// Bind click listener by
//   $('button').live('click', ...)
$(document).on('click', 'button', function() {
  console.log('Click from `live`');
});

// Then create new button,
//   only one message will be appear
//   in console when this button's clicked
$('<button>Unclickable</button>').appendTo(document.body);
            
          

UX breakdown

Tuesday D-E-F

JSONP vs. JSON

Cross Origin Resource Sharing (CORS)

            
$.ajax({
  url: 'http://www.bbc.com/'
})
.success(function(response) {
  // Let's copy the content of BBC and paste it to our page.
  //   so we'll have a pretty live duplication of BBC
  //   with `our own domain`.
  //
  // Lol, we don't need to write / maintain anything, the BBC team
  //   will take care of that, we'll just create some ads/banners
  //   and be happy with easy money
  //
  // What an millionaire idea! And it's crazy simple
  //
  // How about purchasing BBW.com for that superb idea?
  // (Lol, it's not available, and it's not an adult site either)

  $(document.body).html(response);
})
.error(function() {
  // Eck! CORS has just destroyed that crazy idea ...
  // ...

  console.error('.. there is definitely no easy money ..');
})
            
          

JSONP

            
// Suppose we have `jsonp.php` as a simple web service
//   that returns the default password of a company
$.ajax('./playground/jsonp.php').success(function(response) {
  alert('The password is ' + response);
});

// Now if that `jsonp.php` is not on the same domain
//   then CORS will block the browser from dispatching the response
// So how?
// Well, we can modify the response header or implement JSONP,
//   but either way, we have to update the `jsonp.php`

// Let's go with the JSONP file,
//   the JS should be modified like below
function renderTheData(response) {
  alert('The password is ' + response);
}
$('<script src="./playground/jsonp.php?fn=renderTheData"><>').appendTo(document.body);
            
          
            
<?php
// This is the original jsonp.php
echo '0510..';

<?php
// This is the modified jsonp.php to support JSONP
$callback = $_GET['fn'];
echo $callback . '(0510..)'; // should be come renderTheData('0510..') as in our example
            
          

Wednesday D-E-F

Beware, a promise could be rejected.

window.onload and $.ajax

            
// This will be triggered when window load
window.onload = function() {}


// This will be triggered when the DOM has been loaded
//   or the jQuery way $(document).ready(function() {  });
document.addEventListener('DOMContentLoaded', function(){}, false);


// Asynchronous Javascript And Xml
$.ajax('..')
.success(function(response) {
  alert('Success! The response is ' + response);
})
.error(function() {
  alert('Error!');
})
            
          

`Kris Kowal's q` and $.Deferred

            
var process = $.Deffered();
process.then(function(outcome) {
  alert('The result is' + outcome);
});
process.fail(function(err) {
  alert('Oops, error occured. ' + err);
})


// This is a very very long process
//   and include a lot complex processes
var result = !@#!@%!*@%_;

// Cool, we're all done,
//   let's tell them that we finish
process.resolve(result);

// What if instead of having the result
//   we get a mistake, and everything is broken
//   then just tell them we're failed
process.reject(result);

            
          

Thursday D-E-F

Variables are alive.

The var keyword

            
var x = 456;
function aBox() {
  var x = 123;
}
aBox();
console.log(x); // 456
            
          

Lockdown closure

            
// Suppose we have an array of cats
//   and we wanna name a nickname
//   for each of them
//   but we have to ask server first
var cats = ['kitty', 'tom'];

for(var i=0, n=cats.length; i<n; ++i) {
  $.ajax('./what-the-name.php?cat=' + cats[i])
  .success(function(response) {
    cats[i].nickname = response; // Changes are only the last cat get a nickname
                                 //   as the `i` variable at this point
                                 //   usually equals to (n - 1)
  });
}

// It should be something like this
for(var i=0, n=cats.length; i<n; ++i) {
  (function(i) {
    // This `i` is different from the outside i and it's static
    $.ajax('./what-the-name.php?cat=' + cats[i])
    .success(function(response) {
      cats[i].nickname = response;
    });
  })(i);
}
            
          

Friday D-E-F

OOPs! It's everywhere in this context!

OOP like Java: method and attributes

playground/oop.html
            
/**
 * @name Cat
 * @constructor
 * @param {String} name
 * @param {String} country
 * @description
 * We all know about Cat but our Cat will know how to introduce itself
 */
function Cat(name, country) {
  this.name = name;
  this.country = country;
}

/**
 * @name Cat#introduce
 * @method
 * @return {Cat} this
 */
Cat.prototype.introduce = function() {
  alert('This is ' + this.name + ' from ' + this.country);
  return this;
};

var kittyCat = new Cat('Kitty', 'Japan')
  , tomCat = new Cat('Tom', 'US');

kittyCat.introduce();
tomCat.introduce();
            
          

OOP like Java: extend

            
/**
 * @name Animal
 * @constructor
 * @description
 * An Animal know how to eat, sleep, and make love
 */
function Animal() {
}

Animal.prototype.eat = function() {
  alert('Yes, lets eat');
};
Animal.prototype.sleep = function() {
  alert('Yes, lets sleep');
};
Animal.prototype.makeLove = function() {
  alert('Hooray! lets make love');
};

/**
 * @name Cat
 * @constructor
 * @extends Animal
 * @description
 * A Cat is an animal, of course it should know how to eat, sleep, make love
 * .. and introduce itself
 */
function Cat() {
}

Cat.prototype = new Animal(); // Or more proper Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat; // This is optional, but good practice

Cat.prototype.introduce = function() {
  // ...
}
            
          

OOP like Java: public and private

            
function Cat() {
  // Note that these method is usable in this function scope only
  var aPrivateAttribute = null;
  var aPrivateMethod = function() {}

  this.aPublicAttribute = null;
}

Cat.prototype.publicMethod = function() {};
            
          

OOP like Java: static

            
function Cat() {}

/**
 * @name Cat.englishName
 * @type String
 */
Cat.english = 'cat';

/**
 * @name Cat.vietnamese
 * @type String
 */
Cat.vietnamese = 'mèo';
            
          

Saturday D-E-F

XSS, CSRF and JSON Hijacking

Keylogging with XSS

Hacking account with CSRF

JSON Hijacking to bypass CORS

Sunday D-E-F

Regular expression

Just don't worry, those 3-hour long seminar won't be repeated :-D

Feel free to visit the regexp show

QQ . quick quiz

Let's open a browser's console to try these fun snippets

1 + 2 = 3

            
console.log(0.1 + 0.2 === 0.3);
console.log(0.1 + 0.2 == 0.3);
console.log(0.01 + 0.02 == 0.03);
            
          

++_++ and --_--

            
var x = 13;
x = x++;
x = ++x;
console.log(x);

var x = 13;
x = x++ + ++x;
console.log(x);
            
          

Logically says, it's a logical logic

            
var x = 13;
x && (x = x + 7) && (x = x - 20) && (x = 13) && (x++);
console.log(x);

var x = 13;
x || (x = x + 7) || (x = x - 20) || (x = 13) || (x++);
console.log(x);

var x = 13;
(x == x++) && (x = ++x + 1);
(x == ++x) && (x = x++ + 1);
console.log(x);

var success = false;
success && alert('Success!') || alert('Error..');
!!success ? alert('Success again!') : alert('Error again..');
            
          

Everything has its own context

            
function Cat(numberOfLegs) {
  this.numberOfLegs = numberOfLegs;
}

var kittyCat = new Cat(4)
  , tomCat = Cat(5);

console.log(kittyCat.numberOfLegs);
console.log(tomCat.numberOfLegs);
console.log(window.numberOfLegs);
            
          

A few bonus ..

Wanna become a JS mania?

Enjoy it?

Well I don't believe so

Thanks for spending your time the weird way. And again, if you suddenly become another JS lover, feel free to shoot me an email at minhnd.it@gmail.com