javascript Foundation (object)

Keywords: Javascript pink

1. Concept of 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 often expressed in the object (common verb)

"Why do you need objects?"

  • When saving a value, you can use variables. When saving multiple values (a group of values), you can use arrays. What if you save the complete information of one?

  • In order to better store a set of data, object application is born; The attribute name is set for each item of data in the object, which can access the data more semantically, with clear data structure and obvious meaning, which is convenient for developers to use.

  var obj = {
    "name":"fan",
    "sex":"male",
    "age":18,
    "height":155
  }

2. Three ways to create objects

2.1 creating objects with literals

  • The curly braces {} contain the attributes and methods of expressing 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.)

 // 1. Create object {} using object literal
        // var obj = {};  //  An empty object was created 
        var obj = {
                uname: 'Zhang Sanfeng',
                age: 18,
                sex: 'male',
                sayHi: function() { //Anonymous function
                    console.log('hi~');

                }
            }
            // (1) For the attributes or methods inside, we take the form of key value pairs. 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
  • Use of objects

    • Attribute of object: the key in the "key value pair" in which specific data is stored in the object is called the attribute of the object, that is, the item in which specific data is stored in the object.

    • Object method: the "key" in the "key value pair" of the stored function in the object is called the object method, that is, the item of the stored function in the object.

    • Access object's attribute: attribute call in the object: object. Attribute name; Another way to call attributes in an object: Object ['attribute name']. Note that the attributes in square brackets must be quoted.

    • Method of calling object: object. Method name ();

    •   // 2. Object of use
                  // (1) . we call the properties of the object. We take the object name. Property name. We understand it as
              console.log(obj.uname); //Zhang Sanfeng
              // (2) . there is also a method object name ['property name'] for calling properties
              console.log(obj['age']); //18
              // (3) Call the method of the object sayHi object name. Method name () do not forget to add parentheses
              obj.sayHi(); //hi~

      Summary of variables, attributes, functions and methods:

    • ① Variable: independent declaration and assignment, independent existence

    • ② Properties:   The variables in the object are called attributes and do not need to be declared. They are used to describe the characteristics of the object.

    • ③ Method: a method is a part of an object, a function is not a part of an object, and a function is a container that encapsulates operations separately. 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.
    • ④ Function:   If it exists separately, it can be called through "function name ()".
  // 1. The similarities between variables and attributes are used to store data 
        var num = 10;
        var obj = {
            age: 18,
            
        }

        console.log(obj.age);
        // console.log(age);  This is wrong
        difference:
        // 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
 var obj = {
            age: 18,
            fn: function() {

            }
        }

        function fn() {

        }
    
        difference:
        // Functions are declared and called separately: the function name () exists separately
        // When a method is called in an object: object. Method ()

Usual development: call the method function

2.2 creating objects with new Object

  • Create an empty object

  • Add properties and methods to an empty object

<script>
        // Creating objects with new objects
        var obj = new Object(); // An empty object was created
        obj.uname = 'Zhang Sanfeng';
        obj.age = 18;
        obj.sex = 'male';
        // var fun =function() {} add methods like creating function expressions
        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
            // (3) The first letter of object() is capitalized;
            //(4) new Object() requires the new keyword. The format used is: object. Attribute = value
        console.log(obj.uname);
        console.log(obj['sex']);
        obj.sayHi();
    </script>

2.3 creating objects with constructors

    Why do we need to use constructors?
This is because we can only create one object at a time in the previous two methods of creating objects

  <script>
        var ldh = {
            uname: 'Lau Andy',
            age: 55,
            sing: function() {
                console.log('Ice rain');

            }
        }
        var zxy = {
                uname: 'Xue You Zhang',
                age: 58,
                sing: function() {
                    console.log('Li Xianglan');

                }
            }
   // 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, and we call this function constructor
   // And because this function is different, it encapsulates not ordinary code, but objects  
  // Constructor is to abstract some of the same properties and methods in our object and encapsulate them in the function
    </script>

Constructor is a special function, which is mainly used to initialize an object, that is, to assign initial values to object member variables. 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.

  • Encapsulation format of constructor:

 // Syntax format of constructor
        // function constructor name (formal parameter 1, formal parameter 2){
        //     this. Attribute 1 = value;
                this.Attribute 2=value
        //     this. Method = function() {}
        // }
        // new constructor name (argument 1, argument 2);
  • Call format of constructor

var obj = new Constructor name(Argument 1, argument 2, argument 3);
 function Star(uname, age, sex) {
            this.name = uname;
            this.age = age;
            this.sex = sex;
            this.sing = function(song) {
                console.log(this.name + song);

            }
        }
        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')

        // 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

Difference between constructor and object:

  <script>
        // 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(song) {
                console.log(song);

            }
        }
        // 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
    </script>

new keyword execution process:

<script>
        // 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 (so return is not required in the constructor)
        function Star(uname, age, sex) {
            this.name = uname;
            this.age = age;
            this.sex = sex;
            this.sing = function(song) {
                console.log(song);

            }
        }
        var ldh = new Star('Lau Andy', 18, 'male');
        console.log(ldh);
        console.log(ldh.name);
        ldh.sing('Ice rain')
    </script>

3. Traversing objects

The for...in statement is used to perform a circular operation on the attributes of an array or object. (best 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 perhaps key. 
  
  for (var k in obj) {
    console.log(k);      //  there   k   Is the property name
    console.log(obj[k]); //  there   obj[k]   Is the attribute value
}
  // Traversal object 
        var obj = {
                name: 'pink teacher',
                age: 18,
                sex: 'male',
                fn: function() {}
            }

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

        }

Posted by dantheman on Thu, 14 Oct 2021 10:17:35 -0700