Simple and easy to understand-full analysis of javascript objects (1)

Simple and easy to understand-full analysis of javascript objects (1)

Preface


I will look at the javascript authoritative guide for objectdefinitions:

An object is a composite value: it aggregates many values (original values or other objects) together, and these values can be accessed by name. An object can also be seen as an unordered collection of attributes, each attribute is a key/value pair ( key/value). We see most of the reference type values are Objectexamples of the type; and, Objectalso ECMAScriptin one of the most used type. An object is actually a collection of data and functions.

In JavaScriptin a total of six main types:

  string
  number
  boolean
  null
  undefined
  object
 

Of which there are five basic data Undefinedtypes: Null, Boolean, , Numberand String. There is also a complex data type, which is object----- Object.

Null actually represents a pointer to an empty object. This is also the reason why "object" is returned when the typeof operator is used to detect a null value

console.log(typeof null);   //object
 

In fact, JavaScriptthere are many special object subtypes, which can be called complex basic types.

Built-in objects

In addition, JavaScriptthere are some object subtypes in it, usually called built-in objects. The names of some built-in objects look the same as simple basic types, but in fact their relationship is more complicated:

   String
   Number
   Boolean
   Object
   Function
   Array
   Date 
   RegExp 
   Error
 

Built-in objects will continue to be discussed in the next article.

Create an object

1.1 Object literal notation

Create an personobject named :

let person = { 
    name : " ", 
    age : 22 
};
 

When using object literal syntax, the property name can also be a string:

let person = { 
    "name" : " ", 
    "age" : 22, 
};
 

The numeric attribute name here will be automatically converted to a string.

When using object literal syntax, if you leave the curly braces blank, you can define an object that only contains default properties and methods:

let person = {};    //// new Object() 
person.name = " ";
person.age = 22;
 

1.2 Use the new operator to create objects

newThe operator creates and initializes a new object, and the operator is newfollowed by a constructor Object.

let person = new Object(); 
person.name = " "; 
person.age = 22;
 

1.3 Object.create() method

let person = Object.create({name : ' '});
person.name   //
 

Object.create()In fact, an empty object is created and the prototype pointer points to the first parameter passed in.

Object.create = function(new){
    let NewObject = {};
    NewObject.prototype = new;
    return new NewObject();
}
 

Query and setting of attributes

2.1 By way of

let person = {
    name : ' ',
    age : 22
}
//
console.log(person.name);   //
//
person.name = 'guanguan';
console.log(person.name);    //guanguan
 

2.2 By [] notation

let person = {
    name : 'xiaohuanggua',
    age : 22
}
//
console.log(person["name"]);  //xiaohuanggua
//
person["name"] = 'guanguan';
console.log(person["name"]);  //guanguan

//
let newName = "name";
console.log(person[newName]);     //guanguan
 

2.3 Object.keys()

Returns an array containing all attribute names (all keyvalues).

let person = {
    name : 'xiaohuanggua',
    age : 22
}
Object.keys(person);   //["name", "age"]
 

2.4 Object.values()

Returns an array containing all attribute values (all valuevalues).

let person = {
    name : 'xiaohuanggua',
    age : 22
}
Object.values(person);   //["xiaohuanggua", 22]
 

Delete attribute

deleteOperator

You can delete the properties of the object.

let person = {
    name : 'xiaohuanggua',
    age : 22
}
delete person.name;
console.log(person);   //{age: 22}
 

deleteOperators can only delete their own properties, not inherited properties (to delete inherited properties, you must delete them from the prototype object of this property).

deleteThe operator cannot delete falsethe attribute that the configurable item is .

Detection attributes

It is used to detect the belonging relationship among the object members and judge whether a certain attribute exists in a certain object.

3.1 inOperator

If the left-hand attribute (string) is included in the own or inherited attributes of the object on the right, it will be returned true, otherwise it will be returned false.

let person = {
    name : 'xiaohuanggua',
    age : 22
}
let test ="name" in person;
console.log(test);     //true

let test2 ="sex" in person;
console.log(test);     //false
 

3.2 hasOwnProperty() method

It is used to determine whether the property is the own property of the object, the return of the own property, and the return trueof the inherited property false.

let person = {
    name : 'xiaohuanggua',
    age : 22
};
person.hasOwnProperty('name');    //true   person name 
person.hasOwnProperty("sex");     //false  person 
person.hasOwnProperty("toString");   //false   Object   
 

3.3 propertyIsEnumerable() method

Only when the property is the object's own property, and the enumerability of the property is trueyes true, otherwise it is false.

let person = {
    name : 'xiaohuanggua',
    age : 22
};
person.propertyIsEnumerable('name'); 
//true   person name 
person.propertyIsEnumerable('sex');   
//false  person sex 
person.propertyIsEnumerable('toString');  
//false person toString toString person 
 

3.4 !== operator

Determine whether the attribute isundefined

let person = {
    name : 'xiaohuanggua',
    age : 22
};
person.name !== undefined;   //true
person.sex !== undefined;    //false
person.toString !== undefined;   //true
 

However, !==the operator can not distinguish between the presence and absence of property values, but undefinedthe properties, and incan be well distinguished.

let person = {
    name : undefined,
};
//!==
person.name !== undefined;  //false   undefined
person.age !== undefined;   //false   

//in
'name' in person;    //true  undefined
'age' in person;     //false   
 

Enumerated properties

4.1 for..in

let person = {
    name : "xiaohuanggua",
    age : 22,
    sex : 'boy',
};
for(item in person){
    console.log(item);    //name,age,sex 
}
 

for in always gets the key value of the object.

4.2 Object.keys()

Get the attribute names (key values) of all visible attributes of the object, excluding the attributes defined in the prototype.

let person = {
    name : "xiaohuanggua",
    age : 22,
    sex : 'boy',
};
Object.keys(person);   //["name", "age", "sex"]
 

4.3 Object.getOwnPropertyNames()

Get all the properties of the object, excluding the properties defined in the prototype.

let person = {
    name : "xiaohuanggua",
    age : 22,
    sex : 'boy',
};
Object.getOwnPropertyNames(person);   //["name", "age", "sex"]
 

Property get and set

Get: The function to be called when the attribute is read. The default value is undefined.

Set: A function called when writing attributes. The default value is undefined.

let man = {
    name:' ',
    weibo:'@xiaohuanggua',
    get age(){
        return new Date().getFullYear()-1997;
    },
    set age(val){
        console.log(' '+ val);
    }
}
console.log(man.age);     //22      
man.age = 1000;      //1000      
 

Attribute type

Data attributes and accessor attributes.

6.1 Data attributes

The data attribute contains the location of a data value where the value can be read and written.

Data attribute characteristics:

  1. Configurable: Indicates whether modify the characteristics of the property, whether through deletere-re-defined attributes to delete attributes, or the property can be modified to access the properties, the properties of the default value true.

  2. Enumerable: Indicates whether the property can be returned through a loop (enumerable), the default value of this feature true.

  3. Writable: Indicates whether the value of the attribute can be modified. The default value is true.

  4. Value: Contains the data value of this attribute. When reading the attribute value, read from this location; when writing the attribute value, save the new value in this location. The default value of this feature is undefined.

let person = { 
    name: " " ;
}; 
 

Defined directly on the object attributes thereof Configurable, Enumerableand Writableare set to true, and the valuecharacteristic is set to a specified value.

The above example creates a named nameattribute, the value specified for it is " ." In other words, the valuecharacteristic will be set to " ", and any modification to this value will be reflected in this place.

And if you want to modify the properties of the default properties, you must use the Object.defineProperty()method.

This method receives three parameters: the object where the property is located, the name of the property, and an object.

Which attributes of the object must configurablebe: enumerable, , writableand value.

let person = {}; 
Object.defineProperty(person, "name", { 
 writable: false, 
 value: " " 
}); 
alrt(person.name); //" " 
person.name = " "; 
alrt(person.name); //" " 
 

We created a named nameproperty, its value ' ' is read-only. The value of this attribute cannot be modified. If you try to assign a new value to it, the assignment operation is invalid.

let person = {}; 
Object.defineProperty(person, "name", { 
 configurable: false, 
 value: " " 
}); 
alrt(person.name); //" " 
delete person.name; 
alrt(person.name); //" " 
 

Because we will be configurableset to falseindicate the properties can not be deleted from the object, so the delete operation is invalid.

Once an attribute is defined as non-configurable, it cannot be changed back to configurable. So then call the Object.defineProperty()method in addition to modify writablethe characteristics outside, will result in an error:

let person = {}; 
Object.defineProperty(person, "name", { 
 configurable: false, 
 value: " " 
}); 
//
Object.defineProperty(person, "name", { 
 configurable: true, 
 value: " " 
}); 
 

6.2 Accessor properties

Access properties getterand setterfunctions (these two functions are not necessary). When read access properties, will call getterfunction that is responsible for returning a valid value; when writing accessor property, will call setterthe function and pass the new value, this function is responsible for how to handle the data.

It has the following four characteristics:

  1. Configurable: Indicates whether by deletedeleting the property in order to redefine the property, the ability to modify the characteristics of the property, the property is defined directly on the object, the default value of this feature true.
  2. Enumerable: Indicates whether the attribute can be returned through a loop. For attributes defined directly on the object, the default value of this feature is true.
  3. Get: The function to be called when the attribute is read. The default value is undefined.
  4. Set: A function called when writing attributes. The default value is undefined.
let person = { 
    name: ' ', 
    edition: 1 
}; 
Object.defineProperty(person, "year", { 
    get: function(){ 
        return this.name; 
    }, 
    set: function(newValue){ 
        if (newValue > 2019) { 
            this.edition = 2;
        } 
    } 
}); 

person.year = 2020; 
alrt(person.edition); //2 
 

You do not have to specify getterand setter. Specifies that only gettermeans that property is not writable, write property is ignored.

6.3 Define multiple attributes

Object.defineProperties()method. Use this method to define multiple attributes at once.

This method receives two object parameters: the first object is the object whose properties are to be added and modified, and the properties of the second object correspond to the properties to be added or modified in the first object.

E.g:

let person = {}; 
Object.defineProperties(person, { 
    name: { 
        value: ' ' 
    }, 
 
    edition: { 
        value: 1 
    }, 
    year: { 
        get: function(){ 
            return this.name; 
        }, 
        set: function(newValue){ 
            if (newValue > 2004) { 
               this.edition = 1;
            } 
        } 
    } 
}); 

 

In personthe object defines two data attributes ( nameand edition) and an access properties ( year). The final object is the same as the one defined in the previous section. The only difference is that the attributes here are all created at the same time.

6.4 Characteristics of Reading Attributes

Object.getOwnPropertyDescriptor()Method, you can get a description of a given attribute.

This method receives two parameters: the object where the attribute is located and the name of the attribute whose descriptor is to be read. The return value is an object, if access properties, properties of this object are configurable, enumerable, getand set; if data attributes, object attributes are configurable, enumerable, writableand value.

let person = {}; 
Object.defineProperties(person, { 
    name: { 
        value: ' ' 
    }, 
 
    edition: { 
        value: 1 
    }, 
    year: { 
        get: function(){ 
            return this.name; 
        }, 
        set: function(newValue){ 
            if (newValue > 2004) { 
               this.edition = 1;
            } 
        } 
    } 
}); 

let descriptor = Object.getOwnPropertyDescriptor(person, "name"); 
alrt(descriptor.value); // 
alrt(descriptor.configurable); //false 
alrt(typeof descriptor.get); //"undefined"

let descriptor = Object.getOwnPropertyDescriptor(person, "year"); 
alrt(descriptor.value); //undefined 
alrt(descriptor.enumerable); //false 
alrt(typeof descriptor.get); //"function" 
 

Serialized object

The object has two methods: stringify()and parse(). These two methods are used to JavaScriptserialize an object to JSONa string and the JSONstring parsing on native JavaScriptvalues.

//
let obj = {x:1,y:true,z:[1,2,3],nullVal:null};
JSON.stringify(obj);     //"{"x":1,"y":true,"z":[1,2,3],"nullVal":null}"

//undefined, 
let obj = {val:undefined,a:NaN,b:Infinity,c:new Date()};
JSON.stringify(obj);       //"{'a':null,'b':null,'c':2019-06-20T10:32:34}"

//
let obj = JSON.parse('{"x":1}');
obj.x;     //1
 

Object properties

Each object has a prototype ( proto), class ( class), and extensibility ( extensible) related to it. These are the three properties of the object.

Prototype properties

Objects created through object literals are used Object.prototypeas their prototypes;

newUse the prototypeproperties of the constructor function as their prototype by creating objects ;

By Object.create()creating objects using the first argument as their prototype.

    //isPrototypeOf() 
    let person = {x:1,y:2};
    let newPerson = Object.create(person);
    person.isPrototypeOf(newPerson);//true
    Object.prototype.isPrototypeOf(newPerson);//true
 

Class attribute

Used to indicate the type of information object. toString()The class information of the object can only be queried in this way. This method returns a string following format: [object class]. Then extract the characters from the eighth to the penultimate position of the string to obtain the class information.

  1. Objects created by built-in constructors have class attributes that match the name of the constructor.

  2. Pass the object literal and Object.createthe class attribute of the created object is Object.

  3. The class attribute of the object created by the custom constructor is the same Object.

Scalable attributes

Used to indicate whether new properties can be added to the object.

(See attribute type for details)

Object method

9.1 toString() method

toString() Methods can be used to convert the current object into a string form and return the result.

//Object
    let person = {name:' ',age:1000};
    console.log(person.toString()); //[object Object]
//Array
    let array = [" ", true, 12, -5];
    console.log(array.toString()); //,true,12,-5
 

9.2 toLocaleString() method

toLocaleString()The method returns a localized string representing this object. The local time may be the Dateconverted object to a string, and returns the result.

let date = new Date();
console.log(date.toLocaleString()); //2019/8/11  11:51:09
 

9.3 valueOf() method

valueOf() The method is used to return the original value of the specified object.

//Array 
let array = [" ", true, 12, -5];
console.log(array.valueOf());  //[" ", true, 12, -5]
console.log(array.valueOf() === array ); //true

//Object 
let person = {name: " ", age: 18};
console.log(person.valueOf()); //{name: " ", age: 18}
console.log(person.valueOf() === person ); //true
 

9.4 toJSON() method

toJSON()The method returns its own JSONdata format.

// Date   toJSON() 
let d=new Date();
let n=d.toJSON();
console.log(n);  //2019-08-11T16:19:52.681Z

// toJSON() 
 let book = { 
    "title": "Professional JavaScript", 
     "authors": [ 
        "Nicholas C. Zakas" 
    ], 
    edition: 3, 
    year: 2011, 
    toJSON: function(){ 
        return this.title; 
    } 
 }; 
 
let jsonText = JSON.stringify(book); 
console.log(jsonText);  //"Professional JavaScript"
 

toJSON()Can be used as a supplement to function filters. Assuming that an object is passed in JSON.stringify(), the sequence of serializing the object is as follows:

1.   toJSON() 
2.  
3.  
4.  
 

The first half of the subject is over, will the next one be far behind...

This article references:

Javascript advanced programming (third edition)

The Definitive Guide to Javascript (Sixth Edition)