1, Concept of object
Object: unordered collection of name value pairs (collection of key value pairs)
In JS, it can be said that everything is an object:
-
If you store a simple data (a number, a string) directly var a = 10.
-
If we store a pile of data, we think of arrays. Arrays are specially used to store multiple data.
-
If we want to execute a piece of code or make it functional, we need a function.
-
If I want to describe a complex thing, such as a person or a computer (it needs multiple attributes or methods to describe it clearly), I need to use objects at this time.
2, Object creation method
Generally, the objects we talk about are instance objects of objects (universal, general, and can represent anything)
1. Literal creation (common)
var obj = {}; // Defines an object without adding its own properties and methods; // Although there is nothing in this object, it cannot be called an empty object.
Let's create a phone object:
var obj = { name:'iphoneX', color:'black', call:function() { console.log('phone'); } } console.log(obj);
Its results are shown in the following figure:
Let's call the call method of object obj:
obj.call(); // phone
Successfully output "call".
**Note: * * attributes are separated by commas instead of semicolons.
2. Constructor definition (new Object)
var obj = new Object();
As shown in the above code, an object is defined using the constructor method.
It should be noted that:
- If you bring new, the proof is using this function as a constructor.
- If you don't take new, the proof is using this function as an ordinary function.
for instance:
var obj1 = new Object(); // An object is defined without adding attributes, but it cannot be called an empty object. // At this point, obj1 is called an instance Object of Object. var obj2 = new Object({name:'Yang Mi',age:18}); console.log(obj2); var obj3 = { name:'Yang Mi', age:18 } console.log(obj3); // Output obj2 is the same as output obb3 // The final result of a literal definition is the same as that of a constructor definition, and there is no difference in the result.
3. Factory function definition (constructor is still used in essence) (hardly used)
function createObject(name,age) { var obj = new Object(); obj.name = name; obj.age = age; return obj; } // The right values name and age in the name value pair are the name and age in the formal parameter. console.log(createObject('Reba',18)); // Pass argument
3, Object operation (addition, deletion, modification and query) and traversal
A literal definition object is actually the same thing as a constructor definition object
Let's define an object obj, and subsequent operations are performed on it.
var obj = {}; // Equivalent to new Object // This Object is called an Object instance Object
1. Increase
Add attributes directly:
obj.name = 'Xiao Huang'; obj.age = 1; console.log(obj); //age: 1 //name: "Xiao Huang"
We say that there are name value pairs in the object, which is similar to the dictionary in Python. So there is another way to manipulate attributes:
obj["color"] = 'yellow'; obj["category"] = 'Alaska';
If the above [] method is used, adding quotation marks in [] is to add names or keys (name value pairs are also called key value pairs) to the object.
If [] is not added, the content in [] will be treated as a variable. If this variable is not defined, an error will be reported.
for instance:
var obj = {}; var cry = 'call'; obj[cry] = function() { console.log('Woof'); } // Equivalent to obj["call"] = function() {};
2. Change
The operation of change is the same as that of addition, but it follows the principle of "no increase, any change".
obj.color = 'black'; //Change the color to black, add if none, and change if any
obj["name"] = 'Xiao Hei'; //Completely equivalent to obj.name = 'little black'
var a = 'category'; obj[a] = 'Golden hair'; //This process is as follows: first parse a into a variable to see what the value of a is, and then replace a in brackets with the value of a;
3. Check
The query operation can be written directly. If yes, the search is successful, and if no, it is undefined.
console.log(obj.name); //Read the value of the name key in the obj object;
console.log(obj["color"]); //Completely equivalent to obj.color;
var a = 'category'; console.log(obj[a]); //First, parse a bit variable to see what the value of a is, and replace a with the value of A;
console.log(obj.haha); //undefined //If there is no such attribute in the object, the access value is undefined;
4. Delete
The operation of deleting is simple and rough, which can be done by using the delete keyword.
delete obj.category;
delete obj["color"];
var a = 'age'; delete obj[a];
5. Traversal
Traversal is also a query operation, which checks all the attributes of the object.
Note: for is used to traverse the array and for in is used to traverse the object.
Define an object:
var obj = { name:'car', category:'Rolls-Royce', color:'hotpink', money:10000000, run:function() { console.log('Run fast!'); } }
Use for in for traversal:
for(var key in obj) { console.log(key,obj[key]); } // result: // name car // category Rolls Royce // color hotpink // money 10000000 // run ƒ () // { // console.log('running fast! '); // }
Note:
- If you are traversing an object, you can only use [], because key is a variable.
- If it is written as obj.key, you will get undefined, because if it is written in this way, the key will be considered as an attribute in the object.
- obj[key], the key is parsed into a variable and replaced with the value of the variable.
reflection
Why are the output statements console.log() and obj.run() in the above example so similar? Answer - console is also an object.
verification:
console.log(console)
result:
4, Constructor to create a specific instance object
1. Basic concept of constructor
Constructor
The constructor is essentially a function, but usually we write the name of the constructor as a big hump. In the ES5 version of JS, there is no concept of class, and the constructor can be understood as a class.
In Python, objects are generated by class instantiation, so JS can regard the constructor as a class (you can understand the class as the model of the generated object). If I create a constructor called Person, the model will be set. It can only produce human objects, not a dog object. Constructor is to make it easier for us to create multiple objects with the same characteristics.
Constructor usage is the same as ordinary function usage. It can be called directly, but it has one more usage than ordinary functions - new.
case
Define a "human" constructor, so this constructor is the model for generating the human object.
// A constructor, a human model function Person(name,age,gender) { this.name = name; this.age = age; this.gender = gender; this.eat = function() { console.log('having dinner'); } console.log(this); }
What is this?
Usually, this keyword will be used in any function.
This represents the object that calls the function or method (pay attention to the object). The result of this is who owns the function or method at this time. If the function is in the global environment, the result is window, which will be explained in the following (2.window object).
Note: who does this point to score? It will be explained in the following (3. Explanation of this).
Let's call this constructor as an ordinary function:
var a = Person('zs',23,'2'); console.log(result); // Undefined (because the function has no return value) // When the constructor is executed as an ordinary function, this represents window. The meaning of the constructor is to add properties and methods to the window object.
Let's take a look at the result of "console.log(this)" in the function Person at this time:
The name attribute is at the bottom. It is inconvenient to view the screenshot. It also exists in the window object.
We now call this function as a constructor to generate an object (plus new).
Call the constructor and add a new, that is, instantiate the object. It's equivalent to asking the mother of Person to give birth to an object (child) quickly. When it gives birth to an object, what is the name, age and gender of the baby passed to it. Moreover, when new is added, its return value is the instantiated object.
var per1 = new Person('zs','23','male'); console.log(per1); // The result is a per1 object // At this point, per1 can be regarded as a pointer in C language. This originally points to the window, but now new is used. This points to the memory. This represents the space, and per1 is the space address. At this time, this.name=name is equivalent to operating the space name:'zs', and the subsequent operations are the same. Then an instance object is generated and returned, so the result here is the per1 object. // The address is stored in per1. In later modification, per1.name='xx 'is actually found by the address.
Let's look at the results of "console.log(this)" and "console.log(per1)" in the function:
The result is as like as two peas, this is per1 object at this time.
When you point something, the front thing must be an object. When an object points something, it is actually adding or changing attributes to the object.
Therefore, when calling the constructor to instantiate an object, this.xx is to add or change properties to the object currently referred to by this.
new keyword instantiation process:
- Open up memory space
- this points to the memory
- Execution function
- Generate an instance object and return it (although we did not write the return value, it is equivalent to automatically adding return this)
2.window object (global object)
The global object, whose full name is the browser window object, contains everything under the global object when the code is executed.
The functions or variables we directly define in the global environment are all attributes under the global object.
Therefore, we generally call methods under window objects as functions, and methods under other objects are only called methods.
3. Explanation of this
Usually, this keyword will be used in any function.
This is essentially an object, representing the object that calls the function or method (the executor of the function). This stands for who this function or method belongs to.
this points to who gets the score. Generally, there are four situations:
-
In this function, the function can also be called the method of window object. This always represents window;
var a = 10; function add(a,b) { console.log(this); // window return a + b; } console.log(window.add(10,20)); // 30
-
This in the event, this in the callback function represents the event object;
-
This in the method of the object, this represents the object;
obj{ add:function() { console.log(this); //obj } } // Now there is an object called obj, which has a method called add. In fact, add is an attribute of obj, but its value is a function. We call this add an obj method.
-
this represents the instantiated object in the constructor;
4. Constructor instantiation process and memory presentation
Case: singer
function Singer(name,gender,age) { this.name = name; this.gender = gender; this.age = age; this.sing = function(){ console.log('I can sing anything!'); } }
Let's instantiate two powerful singers:
var singer1 = new Singer('Deng Ziqi','famale',28); singer1.sing(); console.log(singer1.name); console.log(singer1['age']);
var singer2 = new Singer('tengger ','male',50); singer2.sing(); console.log(singer2.name); console.log(singer2['age']);
Memory presentation:
Process:
First, push the global environment into the stack area and collect variables from top to bottom (functions also belong to variables).
Then open up memory in the heap and put the function body into memory. Assuming that the address is 100, bind this address to Singer, that is, let Singer point to the memory space with address 100.
Call the constructor Singer to instantiate the object (new). We know that the first step of new is to open up the memory space. Assuming that the memory address of the first new space is 80, this address will be bound to singer1, that is, let singer1 point to the memory space with address 80. At this time, this will also point to the memory space with memory address 80, which is also the second step of new. The third step of new is to execute the function body code and add attributes to the memory space pointed to by the current this. Since single1 is bound to a memory space with a memory address of 80, after the function body code adds attributes to the memory space, the space is the instantiated object.
So we say: the direction of this changes with the operation, and its fundamental function is to help the operation space.