HTML 5

JavaScript

BY
Mohammed Alsaffar
m.9afar@gmail
@9afar on Twitter

Table Of Contents


Objects

1 - Everything is an object

In JavaScript everything is an object except for null and undefined


						false.toString(); // 'false'
						[1, 2, 3].toString(); // '1,2,3'
						function Foo(){}
						Foo.bar = 1;
						Foo.bar; // 1
					

Objects

2 - Objects as a Data Type

Using an object literal - {} notation - it is possible to create a plain object. This new object inherits from Object.prototype


						var foo = {}; // a new empty object
						// a new object with a 'test' property with value 12
						var bar = {test: 12}; 
					

Objects

3 - Accessing Properties

The properties of an object can be accessed in two ways, via either the dot notation or the square bracket notation.


						var foo = {msg: 'hello'}
						foo.msg; // hello
						foo['msg']; // hello
						var VarName = 'msg';
						foo[VarName]; // hello
						foo.1234; // SyntaxError
						foo['1234']; // works
					

Objects

4 - Notation of Keys


    var test = {
        myKey: 'I am a key',
        'case': 'I am a keyword, so I must be notated as a string',
        delete: 'I am a keyword, so me too' // raises SyntaxError
    };
                        
    test.myKey; // I am a key
    test.case;  // I am a keyword, so I must be notated as a string
    

Functions

1 - Declaration


					foo(); // Works because foo was created before this code runs
					function foo() {}
				

The above function gets hoisted before the execution of the program starts; thus, it is available everywhere in the scope it was defined, even if called before the actual definition in the source.

Functions

2 - The function Expression


					var foo = function() {};
				

This example assigns the unnamed and anonymous function to the variable foo.


					foo; // 'undefined'
					foo(); // this raises a TypeError
					var foo = function() {};
				

since assignments only happen at runtime, the value of foo will default to undefined before the corresponding code is executed.

Functions

Example 1


    $(function(){
        // on load code here
    });
    

This is an example of an anonymous function

Functions

Example 2

Result =

    function divide(n1 , n2 , onSuccess , onError){
        try{
            if (n2 == 0) throw "Can not divide by zero";
            var result = n1 / n2;
            onSuccess(result);
        }catch(err){
            console.log(err);
            onError(err);
        }
    }
    
    divide( 1 , 2 ,
        function(result){
            $('#divideValue').css('background','green');
            $('#divideValue').text(result);
        } , 
        function(errorMsg){
            $('#divideValue').css('background','red');
            $('#divideValue').text(errorMsg);
        }
    );
    

Functions

Example 3


    (function(){
        // function calling it self
        alert("Hi, I just called my self!!");
    })();
    

    (// evaluate the function inside the parentheses
      function(){
        // function calling it self
        alert("Hi, I just called my self!!");
      } // and return the function object
    )
    ();// call the result of the evaluation
    

Classes

1 - Using object literals


    var apple = {
        type: "macintosh",
        color: "red",
        getInfo: function () {
            return this.color + ' ' + this.type + ' apple';
        }
    }
                    

In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.


    apple.color = "reddish";
    alert(apple.getInfo());
                    

Classes

2 - Using a function

This is probably one of the most common ways. You define a normal JavaScript function and then create an object by using the new keyword.

To define properties and methods for an object created using function() you use the this keyword, as seen in the following example.

Classes

2 - Using a function

Example


    function Apple (type) {
        this.type = type;
        this.color = "red";
        // anti-pattern! ( this is wrong ) keep reading...
        this.getInfo = getAppleInfo;
    }
 
    function getAppleInfo() {
        return this.color + ' ' + this.type + ' apple';
    }
    
    var apple = new Apple('Red');
    apple.color = "#ff0000";
    alert(apple.getInfo());
    

Classes

3 - The Prototype

JavaScript does not feature a classical inheritance model; instead, it uses a prototypal one.


Class methods should be defined inside the class prototype


    function Apple (type) {
        this.type = type;
        this.color = "red";
    }
                         
    // Instance method will be available to all instances but only load once in memory 
    Apple.prototype.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
                    

Classes

Example 1


    function Greeter(message) {
        this.greeting = message;
        Greeter.prototype.greet = function () {
            return "Hello, " + this.greeting;
        };
    }
                         
    var greeter = new Greeter("GCE");
    $("#GreeterMsg").text(greeter.greet());
                    

Classes

Example 2


    var Greeter = (function(){
                         
        function Greeter(message) {
            this.greeting = message;
        }
                         
        Greeter.prototype.greet = function () {
            return "Hello, " + this.greeting;
        };
                         
        return Greeter;
    })();
                         
    var greeter = new Greeter("GCE");
    $("#GreeterMsg2").text(greeter.greet());
                    

This keyword

The Global Scope

This =

    $("#ThisGSResult").text(this.constructor.name);
                    

This keyword

Calling a Function

This =

    function Test(){
        $("#ThisFResult").text(this.constructor.name);                    
    }
     
    Test();
                    

This keyword

Calling a Constructor

This =

    function Test(){
        $("#ThisCResult").text(this.constructor.name);                    
    }
     
    new Test();
                    

This keyword

Inside Class

This =

    var MyClass = (function(){
        function MyClass() {}
                         
        MyClass.prototype.Test = function () {
            $("#ThisICResult").text(this.constructor.name);
        };
                         
        return MyClass;
    })();
                         
    var myClass = new MyClass();
    myClass.Test();
                    

This keyword

Common Pitfalls

Click Me....

    var MyClass = (function(){
                         
        function MyClass() { 
            $("#clickme").click(this.msg);
            //$("#clickme").click(this.msg.bind(this));
        }
                         
        MyClass.prototype.msg = function () {
            $("#clickme").text("Hello from " + this.constructor.name);
        };
                         
        return MyClass;
    })();
                         
    var myClass = new MyClass();
                    

Static Variables

Example

Counter Result =

    var Counter = (function(){
         
        Counter.Current = 0; // Static Variable
                                                                                                          
        function Counter() {
            this.Current = 0; // Public Variable                
        }
                         
        Counter.prototype.Count = function () {
            Counter.Current++;
            this.Current++;
        };
                         
        return Counter;
    })();
                         
    var counter1 = new Counter();
    var counter2 = new Counter();
                         
    counter1.Count();
    counter1.Count();
    counter2.Count();
                         
    $("#CounterResult").text(Counter.Current);
                    

Inheritance

extends function

Inheritance in javascript is done by adding to the prototype chain and copying property definitions

Using this function


    var __extends = this.__extends || function (d, b) {
        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
        function __() { this.constructor = d; }
        __.prototype = b.prototype;
        d.prototype = new __();
    };
                    

Inheritance

Example


    var __extends = this.__extends || function (d, b) {
        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
        function __() { this.constructor = d; }
        __.prototype = b.prototype;
        d.prototype = new __();
    };
    
    var Animal = (function () {
                         
        function Animal(name) {
            this.name = name;
        }
                         
        Animal.prototype.move = function (meters) {
            alert(this.name + " the " + this.constructor.name +" moved " + meters);
        };
                         
        return Animal;
    })();
                         
    var Snake = (function () {
                         
        var _super = Animal;
        __extends(Snake, _super);
                         
        function Snake(name) {
            _super.call(this, name);
        }
                         
        Snake.prototype.move = function () {
            _super.prototype.move.call(this, 5);
        };
                         
        return Snake;
    })();
 
    var Horse = (function () {
                         
        var _super = Animal;
        __extends(Horse, _super);
                         
        function Horse(name) {
            _super.call(this, name);
        }
                         
        Horse.prototype.move = function () {
            _super.prototype.move.call(this, 45);
        };
                         
        return Horse;
    })();
    
    function TestAnimals(){   
        var sam = new Snake("Sam");
        var tom = new Horse("Tom");
        sam.move();
        tom.move();
    }
                    

Homework 1

Name :
Birthdate :
Favorite Color :

Resources

  1. JavaScript-Garden
  2. mozilla developer JavaScript docs
  3. dailyjs blog
  4. 3 ways to define a JavaScript class
  5. JS Cheat Sheet
  6. JS fiddle

THE END

Fork me on GitHub