JavaScript. Intro to objects

Home » Tutorials » JavaScript » JavaScript. Intro to objects
I continue to consider your comments on my youtube channel and today I pay attention to 39th lesson, which one of you asked me to tell about prototype. But it is not correct to tell about it now. First of all it has the meaning to consider the concept of objects in javascript.
In last lessons, dedicated to javascript, we were considering such types as strings, numbers, boolean and arrays. But in our projects we often need to work not only primitive variables but to store related data (for example, information about men). As you understand, “men” is complex variable, which stores other variables (age, name and so on) within itself. Such complex variable is called object and variables within object are properties. Furthermore object has got methods (functions). Man can go, eat, breathe and so on. This actions are methods. It is better to use term “method”, not function.

Object in javascript is associative array. That’s why you can access to object properties in two ways:

  1. object.name
  2. – access to property in “traditional” object style.

  3. object[‘name’]
  4. – access to property in array style.

Code lesson

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>

    <script>

        var kamil = "kamil";
        var age = 26;

        var kamil = {
            name: "Камиль",
            age: 26,
            birthdate: {
                day: 29,
                month: "июнь",
                year: 1990
            },
            sayName: function() {
                console.log("Меня зовут " + kamil.name);
            }
        };

        kamil.sayName();

        console.log("\n");
        console.log("Копирование объектов и важность this");
        anotherKamil = kamil;
        kamil = null;
        console.log(anotherKamil.sayName());
        console.log(anotherKamil.name);

        console.log("Обращение к свойствам");
        console.log(kamil.birthdate.year);
        console.log(kamil['name']);
        console.log("\n");
        console.log("Перебор свойств:");

        for(prop in kamil) {
            console.log(prop);
        }

        console.log("\n");
        if("prop" in kamil) {
            console.log("Свойство имеется");
        }

        kamil.sayName();
    </script>

    </body>
</html>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This