Most developers have some experience with jQuery, but few of them understand the principles of Javascript and how to write and debug Javascript code. This session will cover best practices for writing object-oriented Javascript, benchmarking, and debugging.
6. Functions
function Person () {
var that = this;
that.age = 0;
setInterval(function growUp () {
// The callback refers to the `that` variable of which
// the value is the expected object.
that.age++;
}, 1000);
}
function Person () {
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
7. The DOM
var titleEl = document.createElement('h1'),
title = document.createTextNode('Welcome to WordCamp DFW!'),
pEl = document.createElement('p'),
aEl = document.createElement('a'),
linkText = document.createTextNode('Click here to find out about the
terrific speakers');
titleEl.appendChild(title);
aEl.href = "https://2017.dfw.wordcamp.org/speakers/";
aEl.target = "_blank";
pEl.appendChild(aEl)
.appendChild(linkText);
document.body.appendChild(titleEl);
document.body.appendChild(pEl);
8. Variable Scope (Global)
<script>
// Counter 1
var x = 0;
setInterval(function() {
console.log( 'Counter 1: ' + x ++ );
}, 1000)
</script>
<script>
// Counter 2
var x = 0;
setInterval(function() {
console.log( 'Counter 2: ' + x ++ );
}, 1000)
</script>
9. Variable Scope (Private)
<script>
(function() {
// Counter 1
var x = 0;
setInterval(function() {
console.log( 'Counter 1: ' + x ++ );
}, 1000)
})();
</script>
<script>
(function() {
// Counter 2
var x = 0;
setInterval(function() {
console.log( 'Counter 2: ' + x ++ );
}, 1000)
})();
</script>