Javascript

The Basics and Confusion

Created by Matt Seigel

Closures

  • Creates scope for your code. 'private' variables.
  • Prevents polluting global/parent's scope
  • Not the same thing as Google Closure
  • Self invoking function are often used in combination with these.

Example Code

We want a counter that doesn't expose its internal counting variable but exposes an add function. No one else should be able to change the count. In this example everyone can access add, but they can also change the counter variable:

                        
var counter = 0;

function add() {
    counter += 1;
}

add();
add();
add();
                        
                    

Example Code

You might try something like this:

                        
function add() {
    var counter = 0;
    function plus() {counter += 1;}
    plus();    
    return counter; 
}
                        
                    

But you aren't able to access the plus function!

Closure Code

Using a self invoking, nested function we can provide the requested behavior. We expose a function called add, but don't expose its internal state variables. We also don't muddy up the global namespace. The () is invoking the add. If you want to pass something into a closed function when self-invoking you can do it here by just putting it in the parathensis.

                        
var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();
add();
add();
                        
                    

Example Code

Another great combination of closure and self invoking function allows you store something that you wouldn't usually have easy access too.

                        
for (var i=1; i<=5; i++) {
    function clickHandler(num) {    
        $("#div" + i).click (
            function() { alert (num) }
        )
    }
    clickHandler(i);
}
                        
                    

Closure Code

A functions variable values are set when the function is called! Now the click event is expecting a function as a handler so return it.

                        
for (var i=1; i<=5; i++) {
    $("#div" + i).click (
        function(num) {
            return function() { alert (num) }
        }(i) // We call the function here, passing in i
    )
}
                        
                    

"Truthy & Falsey"

JavaScripty people like to use these words to describe how things are evaluated to true and false. Booleans don't work the same way in JavaScript as they do in C# or many other languages, but most of it is the same.

Falsey

  • 0
  • undefined
  • null
  • NaN
  • ""
  • false

Truthy

  • 1
  • ANY kind of object
  • new Number(0) is true
  • new Boolean(false) is true
  • Basically, everything not falsey

false, 0 and "" are equivalent

  • false == 0 is true
  • false == "" is true
  • 0 == "" is true

null and undefined are not equivalent to anything except themselves

  • null == false is false
  • null == null is true
  • undefined == undefined is true
  • undefined == null is true

NaN isn't equivalent to anything

  • NaN == null is false
  • NaN == NaN is false

JavaScript classes

Three 'class' structures.

  • Using a function
  • Object literals
  • Singleton via function

Function Definition

  • Define as function
  • Create using new keyword
  • Use this. to specify class methods and properties
                        
function Person (firstName, lastName, sex) {
    this.firstName = firstName;
	this.lastName = lastName;
    this.sex = "male";
}
Person.prototype.getFullName = function getFullName() {
	return this.firstName + ' ' + this.lastName;
};

var luke = new Person('Luke', 'Skywalker');
alert(luke.getFullName());
                        
                    

Object Literals

  • Faster to write
  • No constructor, creates instance immediately
  • Similar to a Singleton
  • JSON!
                        
var luke = {
    firstName: "Luke",
    lastName: "Skywalker",
	sex: "male",
    getFullName: function () {
        return this.firstName + ' ' + this.lastName;
    }
}

alert(luke.getFullName());
						
                    

Singleton via function

  • Combination of the previous
  • Use this. to define methods and properties
                        
var luke = new function() {
    this.firstName = "Luke";
    this.lastName = "Skywalker";
    this.getFullName = function () {
        rreturn this.firstName + ' ' + this.lastName;
    };
}

alert(luke.getFullName());
                        
                    

Libraries

  • Often have their own style
  • Libraries should build on each other under one namespace
  • Varying opinions on the best method

this Confusion

Context Syntax Value of this
Function Baseless function call: func(); window / global
Function Method call: object.func(); object
Function Constructor: var newObj = new Obj newObj
jQuery Event physical click, $el.trigger('click'), etc element that spawned the event

Example

                        
var class = {
    myMethod: function () {
        alert('test');
    }
};

class.myMethod(); // object

var myFunc = class.myMethod;
myFunc(); // window / global
                        
                    

Examples

Manipulating the context

Default context can be manipulated using functions like call, apply, and bind.

Visual Event 2

Example

Questions?

Sources

  • http://howtonode.org/why-use-closure
  • http://www.w3schools.com/
  • http://stackoverflow.com/
  • http://james.padolsey.com/javascript/truthy-falsey/
  • http://www.sitepoint.com/javascript-truthy-falsy
  • http://www.quirksmode.org/js/this.html
  • http://www.digital-web.com/articles/scope_in_javascript/
  • http://stackoverflow.com/questions/3127429/javascript-this-keyword
  • http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

Sources

  • http://sprymedia.co.uk/article/Visual+Event+2
  • http://stackoverflow.com/questions/3127429/javascript-this-keyword