JS object Foundation

preface

Finally, I want to learn from you. For our program apes, we will never be single! No object? Impossible! Just one New, ha ha!!!

No more nonsense. Let's learn JS objects together!

1, What is the object?

Definition: in object-oriented programming, everything is an object! Object is a concrete thing. For example, a star is not an object, but Stephen Chow is an object. The object must be a specific thing! In JavaScript, an object is an unordered collection of related attributes and methods. All things are objects, such as strings, values, arrays, functions, etc.

2, Composition of objects

1. Properties

Attribute: refers to the characteristics of things, which are expressed by attributes in objects (common nouns)

2. Method

Method: refers to the behavior of things, which is expressed by method in the object (commonly used verb)

Example:

//Chinese representation
 One iphone12 Mobile phone (object)
Price (attribute)
9999 Meta (attribute value)
Function: Call (method)

//Code representation
  <script>
        var iphone12 = {  //iphone: object name
            price: 9999, //price: attribute 9999: attribute value
            sendTEL: function () { //method
                console.log("Can I call")
            },
        }
        console.log(iphone12.price);
        console.log(iphone12.sendTEL())
    </script>

The results are shown in the figure below:

3, Creation and use of objects

Three ways to create objects

1. Create objects with literal values

Object literal {} (curly braces), which contains the properties and methods of the object

Example:

 <script>
  	var obj = {
            name:'Zhang San',//name: attribute Zhang San: attribute value
            age:18,		//age: attribute 18: attribute value
            sayHi: function () { //method
                console.log("I can say: hello!")
            },
        }
        console.log(obj.name);	//The first way to get properties: object name Attribute name (be careful not to use quotation marks)
        console.log(obj['age']);//The second way to get attributes: object name ['attribute name'] (note the quotation marks)
        console.log(obj.sayHi());//Get method: object name Method name () be careful not to forget the parentheses
  </script>

The results are shown in the figure below:

Summary:
1. Create object

  1. Create an object with literal {}, and the attributes or methods in it adopt the method of key: value (key value pair)
  2. Multiple attributes or methods are separated by (comma)
  3. The method colon is followed by an anonymous function

2. Use object

  1. (1) Call the properties of the object, using the object name The method of attribute name can be understood as the attribute of the object
  2. (2) When calling the attribute of an object, you can also use the object name ['attribute name'] and pay attention to the quotation marks
  3. Method of calling object: object name Method name (), do not forget to add parentheses

3. Summary of variables, attributes, functions and methods
Variable: declaration, assignment and existence separately
Attribute: 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
Function: it exists alone and can be called by function name ()
Methods: the functions in the object are called methods. Methods do not need to declare and use objects The method name () can be called, and the method is used to describe the behavior and function of the object
Variables and functions need to be declared, and properties and methods can be used directly without declaration

2. Create objects with new Object

    <script>
        var obj = new Object()
        obj.name = 'Zhang Sanfeng';
        obj.age = 18;
        obj.sayHi = function () {
            console.log("I can say: hello!")
        }
        console.log(obj.name);
        console.log(obj['age']);
        console.log(obj.sayHi());
    </script>

The results are shown in the figure below:

Note: new Object() is used here to create the object. The method of = (equal sign) assignment is used to add the object's properties and methods

3. Create objects using constructors

Why do I need to create objects with constructors? Because the first two creation methods can only create one object at a time, please see the following code:

 <script>
        var obj1 = {
            name: 'Zhang Sanfeng',
            age: 18,
            sayHi: function () {
                console.log("hello")
            }
        }
        var obj2 = {
            name: 'Li Si',
            age: 20,
            sayHi: function () {
                console.log("hello")
            }
        }
    </script>

It can be found that the attributes and methods of the created objects are the same. If you need to create many, the efficiency of creating one by one will be very low. However, we can use a function to repeatedly create an object, which is called a constructor. The constructor encapsulates not ordinary code, but objects.
Constructor: it is a special function, which is mainly used to initialize the object, that is, assign the initial value to the object member variable. It is always used together with the new operator. We can extract some public attributes and methods from the object and encapsulate them in this function.

Syntax format of constructor:

function Constructor name(){			//this can be understood as: the
	this.attribute=Value;
	this.method=function(){}
}
Use constructor: new Constructor name            //Note: the constructor name is capitalized
//The object returned by the constructor call is a new object

Example:

<script>						
        function Obj(name, age) {	//Create a constructor and pass in two parameters
            this.name = name;
            this.age = age;
            this.sayHi = function () {
                console.log("hello!");
            }
        }
        var obj1 = new Obj('Zhang San', 18) //Use new to call the constructor and return an object
        console.log(typeof (obj1));   //Use the typeof() function to judge the data type of obj1 and prove that the returned object is the object
        console.log(obj1.name);		 //Get name
        console.log(obj1.age);		//Get age
        console.log(obj1.sayHi());	//Call method
    </script>

The results are shown in the figure below:

Summary:

1. Difference between constructor and object:

  1. Constructors encapsulate the same attributes (common parts) of objects, and generally refer to a large class, such as star / car drawings
    It is similar to the class in java

  2. Object: a specific thing, such as Andy Lau / a real car

2. new keyword executes the process of creating an object by the constructor

  1. Create a new empty object in memory
  2. Let this point to the new object
  3. Execute the code in the constructor and add properties and methods to the object
  4. Return this new object (so return is not required in the constructor)

The process of creating an object through the new keyword also adds the instantiation of the object

4, JS object and JSON object

1. Concepts and differences

Concept: js object is a set of unordered related attributes and methods. json is the representation of js object and a lightweight data exchange format. json is independent of language and platform. It can be read by any programming language and passed as a data format. It is the most widely used standard format in data exchange between server and client.

JS object is not equal to JSON. It is only data in JS object format, not a specific instance object. It is a carrier for cross platform and cross language data transmission, not limited to JS.

difference:

    <script>
        //json
        var obj = {
            "name": "Zhang San",		//json attributes must be quoted
            "age": 18,			//json value cannot be function, undefined, NaN
            "sex": 'male'			
        }
        //js object
        var obj1 = {
            name: 'Zhang San',	//The attributes of js objects can be without quotation marks
            age: 18,		//The attribute values of js objects can be functions, objects, strings, etc
            sex: 'male',
            sayHi: function () {
                console.log("hello!");
            }
        }
    </script>

2.JSON format

Generally speaking, there are two formats:

  1. Object format:
<script>
 //Object format
       var obj1 = {
           "name": 'Zhang San',
           "age": 18,
           "sex": 'male',
     	   }
</script>
  1. Array object format:
<script>
 //Array object format
 	  [
    	   {
           "name": 'Zhang San',
           "age": 18,
           "sex": 'male',
     	   },
     	   {
           "name": 'Wang Wu',
           "age": 17,
           "sex": 'female',
     	   }
      ]
</script>
//This format is often used. You can use loops to traverse the contents

3.JSON conversion

Use JSON Stringify() converts a JS object to a transportable JSON format
Example:

<script>
  //js object
        var obj1 = {
            name: 'Zhang San',
            age: 18,
            sex: 'male',
            sayHi: function () {
                console.log("hello!");
            }
        }
        var newobj1 = JSON.stringify(obj1)	//Convert to json
        console.log(newobj1);
</script>

The results are shown in the figure:

It can be found that the attributes are caused by double quotation marks, but the method is not displayed, which proves that the json value mentioned above cannot be a method function

summary

This content mainly talks about the basic concept of js object, the composition of js object, how to create js object and the difference between js object and json. It introduces the format of json and how to convert js object into json. Next, we will slowly and deeply study the content of js object.

Keywords: Javascript

Added by mistcat on Wed, 02 Mar 2022 01:40:49 +0200