Understanding JavaScript objects

Posted by thehigherentity on Wed, 27 Oct 2021 17:07:10 +0200

catalogue

object

1.1 what is the object

  1.2 why objects are needed

  Three ways to create objects

  two point one   Creating objects with literals

  Object call

  Differences among variables, attributes, functions and methods

  2.2 creating objects with new Object

  2.3 creating objects with constructors

Why do I need a constructor?

2.4 constructors and objects

  3, new keyword

4, Traversal object properties   for...in statement

summary

object

1.1 what is the object

In real life: everything is an object, an object is a concrete thing, a tangible object. For example, a book, a car, a person
It can be "object", a database, a web page, a connection to a remote server, or "object".

In JavaScript, an object is an unordered collection of related attributes and methods. All things are objects, such as strings, values, arrays, functions, etc.  

Objects are composed of properties and methods.

  •   Attribute: the characteristic of a thing, which is represented by an attribute in an object (a common noun)
  • Method: the behavior of things is expressed by method in the object (commonly used verb)

  1.2 why objects are needed

When saving a value, you can use variables, and when saving multiple values (a set of values), you can use arrays. What if you want to save a person's complete information?

The object expression structure in JS is clearer and more powerful. The expression structure of Zhang Sanfeng's personal information in the object is as follows:  

person.name = 'Zhang Sanfeng';
person.sex = 'male';
person.age = 128;
person.height = 154;

  Three ways to create objects

In JavaScript, at this stage, we can create object s in three ways:

  •   Creating objects with literals
  •   Creating objects with new objects
  •   Creating objects with constructors

  two point one   Creating objects with literals

Literal amount of object: curly braces {} contain the properties and methods to express this specific thing (object).
{} is represented in the form of key value pairs

  • Key: equivalent to attribute name
  • Value: equivalent to attribute value and can be any type of value (numeric type, string type, boolean type, function type, etc.)
 // var obj = {};  //  An empty object was created 
        var obj = {
                uname: 'Zhang Sanfeng',
                age: 18,
                sex: 'male',
                sayHi: function() {
                    console.log('hi~');

                }
            }

be careful:  

  •   (1) We take the form of key value pairs for the properties or methods inside   Key attribute name: value   Attribute value
  •   (2) Multiple attributes or methods are separated by commas
  •   (3) The method colon is followed by an anonymous function

  Object call

  •   The attribute call in the object: object. Attribute name, this dot. Is understood as "de"
  •   Another way to call attributes in an object: Object ['attribute name'). Note that the attributes in square brackets must be enclosed in quotation marks, which we will use later
  •   Method call in object: object. Method name (). Note that the method name must be followed by parentheses
   // (1) . we call the properties of the object. We take the object name. Property name. We understand it as
        console.log(obj.uname);
        // (2) . there is also a method object name ['property name'] for calling properties
        console.log(obj['age']);
        // (3) Call the method of the object sayHi object name. Method name () do not forget to add parentheses
        obj.sayHi();

  Differences among variables, attributes, functions and methods

  // Differences among variables, attributes, functions and methods
        // 1. The similarities between variables and attributes are used to store data 
        var num = 10;
        var obj = {
            age: 18,
            fn: function() {

            }
        }

        function fn() {

        }
        console.log(obj.age);
        // console.log(age);

        // Variables are declared and assigned separately. When used, the list of variables is written directly
        // Attributes in an object that do not need to be declared must be object attributes
        // 2. The same point between functions and methods is to realize a function and do something
        // The function is declared separately and the function name () called exists separately
        // When a method is called inside an object, the object. Method ()
  • Variable: independent declaration and assignment, independent existence
  • Attribute: the variables in an object are called attributes and do not need to be declared. They are used to describe the characteristics of the object
  • Function: it exists separately and can be called by "function name ()"
  • Method: the function in the object is called a method. The method does not need to be declared. It can be called by using "object. Method name ()". The method is used to describe the behavior and function of the object.

  2.2 creating objects with new Object

  • Object(): the first letter is capitalized
  • new Object(): the new keyword is required
  • Format used: object. Attribute = value;  
var obj = new Object(); // An empty object was created
        obj.uname = 'Zhang Sanfeng';
        obj.age = 18;
        obj.sex = 'male';
        obj.sayHi = function() {
                console.log('hi~');

            }
            // (1) We use the equal sign = assignment method to add the properties and methods of the object
            // (2) Each property and method ends with a semicolon
        console.log(obj.uname);
        console.log(obj['sex']);
        obj.sayHi();

  2.3 creating objects with constructors

Why do I need a constructor?

This is because we can only create one object at a time in the previous two methods of creating objects

  •   Because we create one object at a time, many of its properties and methods are the same, and we can only copy them
  •   So we can use the method of function to repeat the same code. We call this function constructor because of this     Functions are different. Instead of ordinary code, they encapsulate objects  
  •   Constructor is to abstract some of the same properties and methods in our object and encapsulate them in the function

Constructor: a special function, which is mainly used to initialize an object, that is, to assign an initial value to an object member variable. It is always used together with the new operator. We can extract some public properties and methods from the object and encapsulate them into this function.
In js, you should pay attention to the following two points when using constructors:

  • Constructors are used to create a class of objects whose first letter should be capitalized
  •   Constructors need to be used with new to make sense

Syntax format

 / Syntax format of constructor
          function constructor name (){
          this. Attribute = value;
            this. Method = function() {}
        }
          new constructor name ();

        function Star(uname, age, sex) {
            this.name = uname;
            this.age = age;
            this.sex = sex;
            this.sing = function(sang) {
                console.log(sang);

            }
        }
        var ldh = new Star('Lau Andy', 18, 'male'); // The calling function returns an object
        // console.log(typeof ldh);
        console.log(ldh.name);
        console.log(ldh['sex']);
        ldh.sing('Ice rain');
        var zxy = new Star('Xue You Zhang', 19, 'male');
        console.log(zxy.name);
        console.log(zxy.age);
        zxy.sing('Li Xianglan')

  be careful:

  •         1. The constructor name should be capitalized
  •         2. Our constructor can return results without return
  •         3. We must use new when calling the constructor
  •         4. As long as we call the function of new Star(), we will create an object ldh   {}
  •         5. We must add this before our properties and methods

2.4 constructors and objects

  1.   Constructors, such as Stars(), abstract the common part of the object and encapsulate it into functions. It generally refers to a large class
  2.   Creating objects, such as new Stars(), specifically refers to the process of creating objects through the new keyword, which is also called object instantiation  
// Constructors and objects
        // 1. Constructor refers to a large class, which is similar to the class in java language
        function Star(uname, age, sex) {
            this.name = uname;
            this.age = age;
            this.sex = sex;
            this.sing = function(sang) {
                console.log(sang);

            }
        }
        // 2. Object refers to a specific thing, Andy Lau = = {name: "Andy Lau", age: 18, sex: "male", sing: ƒ}
        var ldh = new Star('Lau Andy', 18, 'male'); // The calling function returns an object
        console.log(ldh);
        // 3. The process of creating objects using constructors is also called object instantiation

  3, new keyword

New does four things when executing:                           New and constructor confirm    :
1. Create a new empty object in memory.                                       1. They gave birth to a baby.
2. Let this point to the new object.                                             2. The baby must be his own this point.
3. Execute the code in the constructor and add properties and methods to the new object.   3. Teach children to read and have a belly of ink.
4. Return the new object (so return is not required in the constructor).     4. Grow up and earn money to repay your parents.
 

   // new keyword execution procedure
        // 1. The new constructor can create an empty object in memory 
        // 2. this will point to the empty object just created
        // 3. Execute the code in the constructor to add properties and methods to the empty object
        // 4. Return this object
        function Star(uname, age, sex) {
            this.name = uname;
            this.age = age;
            this.sex = sex;
            this.sing = function(sang) {
                console.log(sang);

            }
        }
        var ldh = new Star('Lau Andy', 18, 'male');

4, Traversal object properties   for...in statement

  The for...in statement is used to perform a circular operation on the attributes of an array or object.
The syntax is as follows:

for (variable in Object name) {
// Execute code here
}

The variable in the syntax is user-defined. It needs to comply with the naming convention. Usually, we will write this variable as k or key.

for (var k in obj) {
console.log(k); // k here is the attribute name
console.log(obj[k]); // obj[k] here is the attribute value
}

  case

 // Traversal object 
        var obj = {
                name: 'pink teacher',
                age: 18,
                sex: 'male',
                fn: function() {}
            }
            // console.log(obj.name);
            // console.log(obj.age);
            // console.log(obj.sex);
            // for in traverses our objects
            // for (variable in object){

        // }
        for (var k in obj) {
            console.log(k); // The output of k variable is the attribute name
            console.log(obj[k]); // obj[k] gets the attribute value

        }
        // We use the variables in for in. We like to write k or key

summary

    // The object - > {} does not have any attribute name and attribute value, so it is called an empty object
        // Object is used to describe the details of the current thing
        // Object is {key:val,key:val,...} composed of attribute name and attribute value
        // console.log({},[]);

        var stu1 = {
            name: "Woosung ",
            age: 18,
            sex: "male",
            hobby: "female",
            weight: "80kg"
        };

        var car1 = {
            name: "Tricycle",
            width: "2m"
        };

        console.log(stu1);
        console.log(car1);


        // Get the value corresponding to the object property. Without this property, it is equivalent to not defining this property. Return undefined
        console.log(car1.height); //undefined
        console.log(car1["price"]); //undefined

        // Operation of object
        // Giving a value is setting, and not giving a value is getting

        // Dot syntax and bracket syntax
        // set up
        // Object. Attribute name = value;
        // Object [attribute name] = value; attribute names should be wrapped with single or double references, and numbers can be omitted

        // It turns out that if you don't have this attribute, you just add it. If you have this attribute, you just modify it
        car1.price = "10000 element";
        car1["height"] = "2m";
        console.log(car1);

        stu1.age = 22;
        console.log(stu1);

        // obtain
        // Object. Property name
        // Object [attribute name]
        console.log(stu1.name);
        console.log(stu1.age);
        console.log(stu1["sex"]);
        console.log(stu1["hobby"]);

        console.log(car1.height);
        console.log(car1.price);


        // For in loops are generally used to loop through objects
        // Syntax: for(var key in object) {code snippet}
        for (var key in stu1) {
            console.log(key);
            console.log(stu1[key]);
        }

        for (var attr in car1) {
            console.log(attr, car1[attr]);
        }



        var a = 10;
        while (a > 1) {
            if (a == 6) {
                console.log("Hello");
                // continue;
                break;
            }
            console.log(a);
            a--;
        }


        for (var key1 in stu1) {
            if (key1 == "hobby") {
                break;
            }
            console.log(key1);
        }

1. The object can make the code structure clearer
2. Object complex data type object.
3. Essence: an object is a set of unordered related attributes and methods.
4. Constructors generally refer to a large class, such as apples. Whether red apples or green apples, they are collectively referred to as apples.
5. The object instance refers to a thing, such as the apple, the pink teacher who is giving you a lecture, etc.
6. The for... In statement is used to perform a circular operation on the attributes of an object.

Topics: Javascript