More Related Content Similar to The Beauty of Java Script (20) More from Michael Girouard (17) The Beauty of Java Script1. { The Beauty of JavaScript }
Mike Girouard | AjaxWorld 2008
3. I am a
Back-end guy in a front-end guy’s clothes
Sr. Developer at Magnani Caruso Dutton
JavaScript hacker since ’99
JavaScript developer/evangelist since ’07
Speaker: lovemikeg.com/talks
Blogger: lovemikeg.com/blog
15. for (i = 0; i < n; i++) {
// do something
}
17. do {
// something
}
while (i < n);
23. var hexColors = {
‘red’ : 0xFF0000,
‘green’ : 0x00FF00,
‘blue’ : 0x0000FF
};
24. var rgbColors = {
‘red’ : [255, 0, 0],
‘green’ : [0, 255, 0],
‘blue’ : [0, 0, 255]
};
27. var callbacks = {
‘#login-form’ : function () {
// code to validate a login
},
‘#print-btn’ : window.print
};
29. var foo = function () {
return ++foo.counter;
};
foo.counter = 0;
31. var foo = function () {
// do something
};
32. var id = function () {
console.log(this.id);
};
lib.addEvent(foo, ‘click’, id);
lib.addEvent(bar, ‘click’, id);
33. mouseLib.rollOver(
‘some-element’,
function () {
this.src = ‘on.jpg’;
},
function () {
this.src = ‘off.jpg’;
}
);
35. var outer, inner;
outer = function () {
var counter = 0;
inner = function () {
return ++counter;
};
return counter;
};
37. var Foo, Bar;
Foo = function () {};
Foo.prototype.bar = 123;
Bar = function () {};
Bar.prototype = new Foo;
Bar.prototype.bar = 456;
39. var xhr;
xhr = new XMLHttpRequest;
xhr.onreadystatechange = function (event) {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
};
};
xhr.open(‘GET’,document.location.href,true);
xhr.send(null);
50. var addEvent = (function () {
if (window.addEventListener) {
return addW3Event;
}
else if (window.attachEvent) {
return addExplorerEvent;
}
else {
return addLegacyEvent;
}
})();
51. var getXHR = (function () {
if (window.XMLHttpRequest) {
return getW3XHR;
}
else if (window.ActiveXObject) {
return getExplorerXHR;
}
else {
throw ‘No XHR Support.’;
}
})();
53. var myLib = (function () {
var $ = document.getElementById;
var cache = {};
return {
getElement : function (id) {
// do something
}
};
})();
55. var getResource = function () {
var resource, counter;
resource = ‘foo’;
counter = 0;
getResource = function () {
return resource +
‘ has been accessed ’ +
(++counter) + ‘ times’;
};
return getResource();
};
57. var getEmailTemplate = (function () {
var email, link, check;
email = document.createElement(‘div’);
link = document.createElement(‘a’);
check = document.createElement(‘input’);
email.className = ‘email-item’;
email.appendChild(check);
email.appendChild(link);
return function () {
return email.cloneNode(true);
};
})();
59. var d = document;
var byId = d.getElementById;
var byTag = d.getElementsByTagName;
var elements = {
‘foo’ : byId(‘foo’),
‘bar’ : byId(‘foo’).byTag(‘bar’)[0],
‘links’ : byTag(‘a’)
};
63. $$(…) $A(…) $F(…)
$H(…) $R(…) $w(…)