object-oriented

Object 1.

I. Introduction of objects

1. Object concept

An object is a composite data type in which attributes of multiple data types can be stored

2. Object classification

1) Built-in objects: objects defined by the ES standard that can be used in any ES environment such as Math, String, Number, Boolean, Function

2) Host object: the object provided by the JS running environment, currently mainly refers to the object provided by the browser, such as Bom, Dom are browser objects and document objects respectively. There are also common objects console.log,Document.

3) Custom objects: this is the most difficult, because the others are already specified, the main learning is also this, created by the developers themselves.

Create an object

The function called with new is the one that specifically creates the object when constructing the object function construcor.

Format:

varObject variable name =new Object() ;
Copy the code

Example:

var   obj =  new Object  () ; 
console.log( obj) ; 
Copy the code

Console output:

{}[[Prototype]]: Object
Copy the code

New Object() creates an Object(note that Object’s O is uppercase) and instantiates the Object with a variable obj. The object is just an empty object and the variable is not instantiated.

3. Object properties

1. Basic concepts

The values that are stored in an object are called attributes

Format:

Attribute name = attribute value;Copy the code

Example:

var obj.name = "Sun Wukong" ;
Copy the code

Analysis: Similarly, the substance of an attribute is the concrete content. The name of the attribute means that the variable is a container, while the value of the attribute is the real content, equivalent to the literal. From the perspective of object orientation, attribute is the “abstraction” of attribute value, and attribute value is the “concreteness” of attribute.

2. Read properties

Concept: Reading a property is to get the value of the property in the property variable.

Format:

Object. Property nameCopy the code

Example:

// Output Sun Wukong
console.log( obj.name ); / / the Monkey King
Copy the code

Analysis: Use “. To access the property value of the object. Modifying the value of an attribute is equivalent to assigning a new value to the attribute.

3. Delete properties

Format:

delete obj.name
Copy the code

Example:

var obj = new Object() ; // Objects that use new begin in uppercase
obj.name = "Sun Wukong" ;
console.log("Name before delete:" + obj.name) ; // Delete previous name: Sun Wukong
delete obj.name
console.log("Name:" + obj.name) ; // Name: undefined
Copy the code

Delete obj. Name = ‘obj’; obj = ‘obj’;

4. Representation of attribute variables

There are many ways to express attributes (variables)

Identifier naming rules are not mandatory for attribute variable names of objects, but special names cannot be used if required. To access an attribute value, use the object name [” attribute name “].

Format:

varAttribute variable =new Object() ;
// Access to modify attribute valuesAttribute variable name [old attribute value] ="New property value" ;
Copy the code

Example:

var obj = new Object(a); obj["Name"] = "Sun Wukong";
console.log(obj["Name"]); / / the Monkey King
Copy the code

Analysis: then the name is the attribute name, and Sun Wukong is the attribute value.

The attribute name in this method [] can also be a variable, making it more flexible to use than the default method of adding attribute values. Js object property name, can be any data type (including object)

The IN operator

Function: Checks whether an object contains a specified attribute, and returns true if it does, or flase otherwise.

Format:

attributeinObject variablesCopy the code

Example:

// Check if obj contains test1
var obj = new Object(a); obj["Name"] = "Sun Wukong";
console.log(obj["Name"]); / / the Monkey King
console.log(  "Name"  in  obj); // true
console.log(  "Age"  in  obj); // false
Copy the code

Data types and reference types

1. Basic data types

The values of basic data types are stored directly in stack memory and are independent of each other. Modifying one variable does not affect the other.

var a = 123;
var b = a;
console.log("Value of B:" + b); // b value: 123
Copy the code

Analysis: A first assigns 123, then B assigns the value of A. B 123 has nothing to do with A 123, it just looks the same, it’s independent.

2. Reference data types (objects)

var obj1 = new Object(a);var obj2 = new Object(a); obj1.name ="Sun Wukong" ;
obj2 = obj1;
console.log("Obj1 name:" + obj1.name ) ; // Obj1's name: Sun Wukong
console.log("Obj12 name:" + obj2.name ) ; // Obj12's name: Monkey King
// Change obj2's name
obj2.name = "Pig Eight Quit" ;
console.log("Obj1 name:" + obj1.name ) ; // obj1's name: pigbajie
console.log("Obj12 name:" + obj2.name ) ; // obj12's name: pig
Copy the code

Obj1’s name is changed because obj1 and obj2 refer to the same region in memory.

The first time you create an obj1 object, you actually create a space and assign the address 0x99 of the space to a variable, which is the object variable obj1. Obj2 = obj1; , “pass” the value 0x99 of the variable obj1 to obj2, which causes obj1 and obj2 to point to the same memory space. Obj2. name = “pig eight Quit”; Obj1 and obj2 have the name attribute of the memory space pointed to by 0x99. Obj1 and obj2 have the name attribute of the memory space pointed by 0x99.

3. Another way to create objects

Another way to create an object is to create an object using its literal.

Format:

// Create objects using literals
varAttribute variable = {};// Create an object with new
varAttribute variable =new Object(a);Copy the code

Example:

/ / create
var obj1 = {} ;
// Create and assign
var obj2 = {name:"Pig Eight Quit"};
console.log("Obj2 name:" + obj2.name); // Obj2's name: Pig
Copy the code

Analysis: The essence of the two ways is the same. But using object literals is a little bit easier when you’re creating an object and you can assign values to properties. If there are multiple attributes, separate name-value pairs with commas (,). Objects are created in the same way that object literals are commonly used in development


Method 2.

1. Method concept

Methods are “functions” from an object-oriented perspective.

2. Method of use

// Create an object
var obj = new Object ()  ;

// Add attributes to the object
obj.name  =  "Sun Wukong";
obj.age  = 18;
Copy the code

The attributes in an object can be of any type, with special time objects, functions… .

obj.sayName = function ( ) {
   console.log( obj.name  );
};
Copy the code

The property of the object is a function. One use of the function object (named function) approach is to call a function

Format:

Object. Method name ();Copy the code

Example:

obj.sayName( );
Copy the code
// Create an object
var obj = new Object(a);// Add attributes to objects (base types)
obj.name = "Sun Wukong";
obj.age = 18;

// Add attributes (functions) to the object
obj.sayName = function () {
    console.log("name: " +  obj.name);
};
// How to use it
obj.sayName(); // Name: Sun Wukong
Copy the code

The object prints its property name using its own sayName method. The creation function here is in the form of a variable.

If you call a function in the normal form, it has an object, which is the window. Of course, the function in the above example is assigned to an object (in fact, to the object’s property 🤣), so the function object is obj.

If a function is a property of an object (as in the example above), then. So let’s call this a method of this object


3. Enumerate properties in the object

Concept: Enumeration objects create objects in literal form, in the form of “name-value pairs,” neatly formatted, one by one.

// Create a function with a function literal
var obj = {
   name : "Sun Wukong".age : 18.gender : "Male".address : "Flower and Fruit Hill"
};
Copy the code

🚀T- Tests the properties of the traversal output enumeration object.

// Create a function with a function literal
var obj = {
    name: "Sun Wukong".age: 18.gender: "Male".address: "Flower and Fruit Hill"};// The for loop iterates over the output enumeration of object properties
for(var n in obj) {
    console.log(n);
}
Copy the code

Console output:

name
age
gender
address
Copy the code

Analysis: The “for in” statement is used to iterate over content in the form of a “collection”.

🚀T- Test traversal outputs the property values of the enumeration object.

// Create a function with a function literal
var obj = {
    name: "Sun Wukong".age: 18.gender: "Male".address: "Flower and Fruit Hill"};// The for loop iterates over the output enumeration of object properties
for(var n in obj) {
    console.log(obj[n]);
}
Copy the code

Console output:

The Monkey King18male Huaguo mountainCopy the code

For in loop, n represents a certain attribute in the obj attribute set, is a variable, each cycle of the attribute becomes the next attribute, using the obj[attribute] form to obtain the attribute value.

Window objects are created by the browser methods that are created in the global scope, functions that can be properties, methods of the window object. Global functions are stored as window methods


4. Declare symptoms in advance

1. Variable declarations are advanced

Case 1: Use var to define variable A and then use console.log() to print the value of a.

var a = 3;
console.log("a = " + a ); // a = 3
Copy the code

Var = var; var = var; var = var

Case 2: Reverse the upper and lower statements. A strange effect occurs when a var declaration variable is placed after the statement that calls it.

console.log("a = " + a ); // a = undefined
var a = 3;
Copy the code

Effect: There is no error in variable A, but the value is undefined.

Analysis:

Case 3: Remove the var declaration based on case 2 (when declaring variables without var comes after statements that use variables).

console.log("a = " + a ); // a = undefined
a = 3;
Copy the code

Effect:

If the statement part of the variable declaration is after (below) the statement in which the variable is used, the program executes the statement with var first, but does not assign a value, so the value of case 2 is undefined. In case 3, after var is removed, variable A is not defined and declared, that is, a is illegal, which will cause an error.

The compiler preprocesses the var to float on top of it. However, variables should follow the principle of declaration assignment, use later (top to bottom).

If the compiler does not “see “var, an error will be reported if the variable has not been declared.

2. Function declarations are advanced

It’s the same thing as a variable, almost the same thing

var a = 3;
var b = 4;

fun1();
function fun1(){
    console.log("a = " + a);
}

fun2();
var fun2 = function(){
    console.log("b = " + b);
}
Copy the code

Effect:

(after)


5. Context object this


6. Create objects using factory methods

1. Brief introduction of factory methods

Concept: The factory approach is to create a “template” that performs repetitive tasks with individual parameters.

Purpose: Create a class

2. Factory method creation

1) Create object without using factory method (create object literal)

var  obj  = {
    name  : "Sun Wukong".age  : 18.gender  : "Male".address  : "Flower and Fruit Hill"
    sayName :  function( ) {};Copy the code

This is a very flexible way to create objects in literal form, and to copy properties at the same time. But there are problems with this approach. When there are a lot of requirements to create objects, this approach can be tedious. In fact, the type and number of attributes of such objects are basically fixed, and the change is only reflected in the specific attribute value, that is, the process of creating a new object only needs to change the attribute value. Different contents with repeated structures but fixed positions can be encapsulated as functions and processed in batches to improve efficiency.

2) Use factory method to batch create objects

function creartePerson(){
	/ / the function body
    // Create object function statements
    // Return the object
    return obj;
}

creartePerson();
Copy the code

Analysis: Want to achieve this effect. Use the creartePerson (); Pass arguments, inside the function to complete the structure and attribute value assignment.

Completion body

function createPerson ( name ,age ,gender ,address ) { 
	var obj = new Object(a); obj.name = name; obj.age =age; obj.gender = gender ; obj.address =address; obj.sayName =function () { 
	alert(this.name);
   }
return obj;
};

createPerson(); // Different parameter values can be passed when called
Copy the code

The createPerson function is the factory that creates the object, and obj is the template, which is the class.


constructors

1. Use constructors to create objects

Use:

// Create a template
function Person(){ This is a class of things
   console.log(this);
}


// Create object PSN
var psn = new Person(); // This per is equivalent to an instance
Copy the code

Console output:

Person{}
   _proto_:Object
Copy the code

This is PSN

Constructor execution flow:

  1. Constructor innovation object
  2. The new object will be the function this
  3. Execute the code line by line
  4. Create a new object as the return value

So in the previous construction of a function, creating a function object in the new way is actually a constructor.

3, instanceof

Concept: use instanceof to determine whether an object is an instanceof a class

// Create a constructor
function Person(){
    console.log(this);
}

// Create an object
var psn = new Person();

// Determine whether PSN belongs to the Person class
console.log(psn instanceof Person);
Copy the code

Effect:

Notes and Details:

  • Constructor starts with a capital letter
  • Ordinary functions are called directly
  • The constructor is called using the New keyword
  • Object is the parent of all classes

4. Constructor modification

Constructors are good, but there are some problems.

The method in the constructor is to create a new method within it every time it is executed. If it is executed 10,000 times, that is to create 10,000 methods, the key is that the methods are all the same. So can we take these same methods and call them shared methods.

1) Make methods public: write methods to global scope

  • Defining a function in a global scope pollutes the global scope space.
  • Unsafe, the same function name, easy to rewrite, overwrite.

8. Prototype objects

Introduce a conceptual prototype

Temporary slightly…

9. The toString () method

ToSting () is a prototype method that can be overridden by objects

Temporary slightly…

10. Garbage collection mechanism

Set objects that do not apply to NULL

Temporary slightly…

(after)