הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

JavaScript 1

JavaScript Variable Types

Variable Type Declaration Usage Comments
Number var x = 3; var z = x + 5;  
String var name = 'John'; var fullname = name + ' Doe'; Use inside single or double quotes
Boolean var is_happy = true; if ( is_happy ) { clap_your_hands(); }  
Function var add_five = function(x) { return x + 5; } var seven = add_five(2); Using a function is the act of "calling" it, and performed with () after its name. The return value of the function will be assigned to the variable on the left
Objects var o = { top: 10, left: 20 }; alert(o.top + o.left); An object is a collection of values, each is identified by a name. The value can be of any JS type.
Arrays var arr = [1, 2, 'a', 'b']; arr[0] + arr[1]; An array is a collection of values, each identified by its position in the array (starting with zero)

Creating JavaScript Objects

A simple object in JavaScript is a collection of variables under a single name.


(function() {
    
    var pet = {
        name: 'Moris',
        is_a: 'cat'
    };
    
    // prints I have a pet named Moris
    console.log('I have a pet named ' + pet.name);
    
}());

Passing Objects as Arguments

Since objects are just normal data type, we can pass them as arguments to functions.
These functions can work with all the keys in the object.

In the following example, we define two objects passing them to the feed function.
The function changes an attribute of the object, and that change is reflected after the call.


(function() {
    var feed = function(pet) {
        pet.size += 1;
        console.log('Yummy');
    };
    
    
    var cat = {
        name: 'Moris',
        size: 2
    };
    
    var dog = {
        name: 'Lassy',
        size: 1
    };
    
    feed(cat);
    feed(cat);
    feed(dog);
    
    // prints 4
    console.log(cat.size);
    
    // prints 2
    console.log(dog.size);
}());


Creating Functions Inside an Object

Since objects are a collection of variables, and functions are simple data types, it's very easy to nest functions inside objects.
All it takes is to declare the function as the value for a certain key.

In the following example, functions are created as part of the object and later called in a normal way.


(function() {
    
    // The object has two fields, one is named "name" and has
    // the value "Luke"; The other has the name "hello" and
    // has the a function as its value.
    // We can call the function by using person.hello()
    var person = {
        name: 'Luke',        
        hello: function() { console.log('Hello World'); }        
    };
    
    // The object has 3 fields: two numeric fields height and
    // width, and the last field is a function.
    // The function uses some other attributes of the object
    // to perform its calculation
    var rect = {
        width: 10,
        height: 20,
        area: function() { return rect.width * rect.height }
    };


    // print "Hello World"
    person.hello();
    
    // print "The area is 200"
    console.log('The area is: ' + rect.area());
    
    // This one is a bit surprising, it prints:
    // The area is: function () { return rect.width * rect.height }
    // The reason is we print _the function_ instead of calling
    // it and print the value
    console.log('The area is: ' + rect.area);
    
}());


DOM Examples

Disappearing sentence html

<!DOCTYPE html>
<html>
    <head>
        <title>Hello DOM</title>
        <style>
            .box {
                width: 200px;
                height: 200px;
                border: 10px solid #ccc;
                background: 222;
                float: left;
            }
            #container {
                width: 500px;
            }
        </style>
    </head>
    
    
    
    <body>
        <div id="container">
            <div class="box" sentence-number="1"></div>
            <div class="box" sentence-number="2"></div>
            <div class="box" sentence-number="3"></div>
            <div class="box" sentence-number="4"></div>
        </div>
        
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <script src="app.js"></script>
        
    </body>
</html>

And js


(function() {
    'use strict';

    var sentences = [
        'Hello',
        'The secret',
        'Password is',
        'Hello'
    ];

    var show_sentence = function(div) {
        var num = Number(div.attr('sentence-number'));
        div.html(sentences[num - 1]);
    };
    
    var hide_sentence = function(div) {
        div.html('');  
    };

    var on_click = function() {
        var clicked_div = $(this);        
        var text = $(this).html();
        
        if ( text === '' ) {
            show_sentence(clicked_div);
        } else {
            hide_sentence(clicked_div);
        }
    };
    
    $('#container div').bind('click', on_click);
}());

course: