1 object

1.1 Why Objects What are Objects

1.1.1 Why Objects

Object presentation structure is clearer and more powerful.

Save a value, use a variable; Store multiple values, using arrays; Save complete information about a person with objects.

1.1.2 object

An object is a concrete thing, not a generalization. In JavaScript, an object is an unordered collection of related properties and methods, and everything is an object. For example, strings, numbers, arrays, functions, etc. Objects are made up of properties and methods:

  • Attribute: A characteristic of a thing, represented in an object by an attribute (common noun).
  • Method: The act of a thing, expressed as a method in an object (often a verb).

An object is a collection of properties that contain a key or name and a value.

// Object literals; The key must be a string
let folder1 = {
    'size': 2000.'name': 'folder1'.'subFiles': ['index.js'].'other object': null
};
// console.log(typeof folder1, folder1);

// If it is a valid identifier, you can omit the quotation marks:
let folder2 = {
    size: 2000.name: 'folder2'.subFiles: ['index.js'].'other object': folder1
};
Copy the code

1.2 Variables, attributes, functions and methods

The main function The statement use
variable Store the data Declare and assign separately Just write the variable name
attribute Store the data Properties in objects do not need to be declared Object. Properties
function Implement a function A separate statement The function name ()
methods Implement a function Methods in objects do not need to be declared Object.method ()
  • An attribute of an object whose value is a function is called a method of the object.

1.3 Add, delete, modify, and check object attributes

  • Invoke properties of the object
    • Object name. Attribute name
    • Object name [‘ Property name ‘]
  • Call a method of an object
    • Object name. Method name ()

1.3.1 Access (Search)

// Access object property: 1️ discount.
console.log(folder2.size, folder2.name);

// Or use 2️ one: []
console.log(folder2['size'], folder2['name'], folder2['other object']);
// [] Can be filled with any valid value (expression)
let sizeKey = 'size';
console.log(folder2[sizeKey], folder2['na' + 'me']);

// 3️ discount
console.log(folder2["other object"].subFiles[0]);

// If an attribute does not exist, undefined is returned
console.log(folder2.data, folder2['any' + 'string']);

Copy the code
  • Note: the ellipsis of the object
    // A more concise way of writing
    const year = 2020;
    const month = 6;
    console.log({
        // Attribute name is variable name, value is variable value, do not write year: year.
        year,
        month,
    
        / / method
        print() {
            console.log(year + The '-'+ month); }})Copy the code

1.3.2 modify

  • Property values can be modified at will
    folder2.size = folder2.size + 1000;
    folder2['name'] = null;
    folder2.subFiles = [];
    console.log(folder2.size, folder2.name, folder2.subFiles);
    Copy the code
  • The attributes of an object are mutable, and more attributes can be added
    folder2.createTime = '2020-6-1';
    folder2['modifyTime'] = '2020-6-15';
    console.log(folder2);
    Copy the code
  • When writing directly to object literals, you want property names to be computed, not fixed. We should define a variable first:
    const str = 'variable';
    const obj = {
        // The property name is variable
        [str]: 'computed key'.// Numbers will not be converted to strings
        0.1: 'number as key'.log: () = > {
            console.log('func as value'); }}console.log(obj.variable, obj[str]);
    
    // Numbers are converted to strings
    console.log(obj['0.1'], obj[0.1]);/ / obj. 0.1 ❌
    
    obj.log();The functions that an object contains are also called methods
    Copy the code

1.3.3 Traversing object Properties

for… In uses the variable in for in, usually k or key

const student = {
    name : 'Joe'.age : 20.interests : ['running'.'read'].teacher: {
        name: 'bill'}};// 1️ one: Key method
//Object is a global Object provided by JavaScript
console.log(Object.keys(student));//["name", "age", "interests", "teacher"]

/ / 2 ️ ⃣ : for in
for (const key in student) {
    console.log(key, student[key]);
}
Copy the code

1.3.4 Determining whether an object contains an attribute

console.log(student.classmate === undefined); // ❌, there may be an attribute with a value of undefined

//1️ discount
Object.keys(student) 

//2️ one: use in
console.log('classmate' in student, 'teacher' in student);
Copy the code

1.3.5 Deleting Attributes

// Attribute delete, delete
delete student.teacher;
console.log('classmate' in student, 'teacher' in student);
Copy the code

2 Object reference

2.1

  • A variable holds an object, holds a reference to that object, or the variable refers to that object.
    const emptyObj1 = {};
    const emptyObj2 = {};
    console.log(emptyObj1 ! == emptyObj2);//ture
    
    const emptyObj3 = emptyObj1;// Assign an object to a variable, copy the reference relationship
    console.log(emptyObj1 === emptyObj3);//true
    
    emptyObj1.id = 'emptyObj1.id';
    console.log(emptyObj1.id, emptyObj2.id, emptyObj3.id);//emptyObj1.id undefined emptyObj1.id
    Copy the code
  • Const defines an object, which guarantees the immutability of references (that is, the immutable pointing relationship), but the object’s properties are mutable. Using let references changes.
    //emptyObj1 = emptyObj2; / / ❌
    let emptyObj4 = emptyObj1;
    console.log(emptyObj4.id);//emptyObj1.id
    emptyObj4 = emptyObj2;
    console.log(emptyObj4.id);//undefined
    Copy the code

2.2

  • For a function parameter, the value is passed in; for an object, the value is passed in as a reference to the object.
  • Changing a reference to an object or a variable in a function is equivalent to changing only the reference relationship of the function parameters. The reference relationship of the outer layer is unchanged, and so are the outer variables.
    // The parameter is passed in as a value; For objects, reference
    function changeParam(basicValue, object) {
        console.log('Before change', basicValue, object);
        basicValue = undefined;
        object = null;
        console.log('After change', basicValue, object);
    }
    changeParam(1, emptyObj1);
    {id: "emptyobj1.id "}
    // undefined null
    
    console.log(emptyObj1);//{id: "emptyObj1.id"}
    Copy the code

2.3

  • The immutable reference relationship does not mean that the object’s content is immutable.
    function addProperty(object) {
        const key = '__private__key__';
        object[key] = 'from addProperty func';
    }
    addProperty(emptyObj2);
    console.log(emptyObj2);//{__private__key__: "from addProperty func"}
    Copy the code

3 Three methods of creating an object

3.1 Use object literals

  • {}
    var obj = {};
    var obj1 = {
        uname: 'niki'.age: 18.//1. Key-value pair form
        sex: 'woman'.//2. Separate by commas
        sayHi: function() { //3. Method colon followed by anonymous function
            console.log('hi~'); }}console.log(obj.uname);
    Copy the code

3.2 Using new Objects

  • Add attributes and methods to the object using the equal sign assignment method.
  • Between each property and method;The end.
    var obj = new Object(a); obj.uname ='niki';
    obj.age = 18;
    obj.sex = 'woman';
    obj.sayHi = function() { 
        console.log('hi~');
    }
    console.log(obj.uname);
    console.log(obj['sex']);
    obj.sayHi();
    Copy the code

3.3 Use constructors

A constructor abstracts some of the same properties and methods from our object and encapsulates them in a function.

A constructor is a special function used to initialize an object, that is, to assign initial values to an object’s member variables. It is always used with the new operator.

Why use constructors to create objects?

  • 🧷 Only one object can be created at a time. Many properties and methods of many objects are largely the same and can only be created repeatedly, one after another.
  • 🧷 calls this function a constructor by repeating the same code using the method of the function.
  • The 🧷 constructor encapsulates objects rather than ordinary code.

Constructor syntax format

functionConstructor name () {
    this.attribute = value;thisDirection:.function() {}}newConstructor name ();Copy the code
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('liudehua'.18.'male');
ldh.sing('freezing rain')
var zxy = new Star('zhangxueyou'.19.'male');// Batch production
Copy the code

Note:

  • Use a capital letter for constructor names.
  • The constructor returns the result without a return.
  • The constructor must be called using new.
  • As soon as new Star() calls the function, an object is created.
  • Properties and methods must be preceded by this.

The difference between constructors and objects

A constructor is a generic class similar to a Class in Java.

An object is something concrete in particular

The process of creating an object using a constructor through the new keyword is called instantiation of the object.

New keyword execution process

  1. The new constructor creates an empty object in memory.
  2. This points to the empty object you just created.
  3. Execute the code in the constructor to add properties and methods to the empty object.
  4. Return this object. (So the constructor doesn’t need a return)

4. A deep-copy case

function clone(parent) {
    const allParents = [];
    const allChildren = [];

    function _clone(parent) {
        const child = {};
        if (parent === null) {
            return null;
        }
        if (typeofparent ! = ='object') {
            return parent;
        }
        const index = allParents.indexOf(parent);
        if(index ! = = -1) {
            return allChildren[index];
        }
        //🚀 avoid infinite recursion caused by circular references
        allParents.push(parent);
        allChildren.push(child);
        for (const key in parent) {
            const value = parent[key];
            child[key] = _clone(value);
        }
        return child;
    }
    return _clone(parent);
}
console.log(
    clone(undefined),
    clone(null),
    clone(1),
    clone(' '),
    clone({}),
    clone({id: 1.obj: {id: 2}}));const circularObj = {};
circularObj.self = circularObj;
console.log(clone(circularObj));
Copy the code