头图

object

It is a collection of unordered attributes, and its attributes can contain basic values, objects, or functions. You can think of objects as hash tables: key-value pairs, where the values ​​can be data or functions. Objects in ECMAScript are actually a set of data (attributes) and functions (methods).

Digression: Sleep, do it tomorrow, happy Mid-Autumn Festival duck! ! ! ! !

An object is a collection containing related data and methods (usually composed of some variables and functions, which we call the properties and methods in the object)

For example, in real life, everyone is an object. Objects have attributes, such as height and weight, and methods such as walking or running; everyone has these attributes, but everyone’s attributes are different. Everyone has these methods, but the time when the methods are executed varies. All the same.

  • In JavaScript, almost everything is an object.

The following code person to "Zhang San":

var person = "Zhang San";

  • The object is also a variable, but the object can contain multiple values ​​(multiple variables), and each value is presented as a key:value key-value pair.
var person = {
   //注意属性和属性之间用逗号隔开
    name:"张三", 
    height:1.71, 
    gender: 'male'
};

Object creation

objects, constructor mode and literal mode

  • literal mode

The object uses "{}" as the boundary of the object. The object is composed of multiple attributes. Attributes and attributes are separated by ",", and attribute names and attribute values ​​are separated by ":"; attribute names generally do not add quotation marks ( When special characters appear in the attribute name, you need to add quotation marks), if the attribute value is a string, you must add quotation marks

E.g:

var obj = {
  name:"terry",
  age:12,
  sayName:function(){
    console.log("my name is ",this.name);
  }
}
  • Constructor mode

Use Object or use a custom constructor to initialize the object

var obj = new Object();
  obj.name = "terry";
  obj.age = 12;
  //sayName是obj对象的一个方法,可以看作是obj的一个属性
  obj.sayName = function(){
  console.log("my name is",this.name);
}
//等价于 <==>
var obj={};
  obj.name="terry";
  obj.age=12;

object access

  • property access

There are also two ways to access attributes, point access and bracket access

The property of the object is directly followed by the dot. If the property exists, it can be accessed. If the property does not exist, it will get undefined. The variable is placed in the square brackets, and the square brackets can parse the variable.

E.g

obj.name      //'terry'
obj['name']     //'terry'

name = "age"
obj['name']      //12
  • Method access

Method access is mainly to execute the method in the object, which needs to be used in the way of function calls

E.g

 var obj = {
     name: 'zhang',
     age: 13,
     sayName: function () {
          console.log(this.name);   //zhang
     }
}
obj.sayName();//zhang    //obj方法的使用

obj.sayName; //访问的是obj对象的方法
console.log(obj.sayName); //[Function: sayName]

  • Traverse the attributes in the object

The normal version of the for loop can traverse arrays, but cannot traverse objects

Enhanced for loop: for..in is used to traverse the properties of an array or object

(Off-topic: Before the classmate area interviewed Jingdong's front-end internship, the interviewer asked about this...)

for(自定义变量名 in 数组/对象){
    执行代码
}
for(var key in obj){
    var value=obj[key];
}

Example usage:

// 增强版的for循环:
//循环对象属性:
var obj = {
     name:"autumn",
     age:22,
     salary:10000
   };
// for..in用于遍历数组或者对象的属性
for (var key in obj) {
     console.log(key + '-------' + obj[key]);
     //name-------autumn
     // age-------22
     // salary-------10000
}

Add and delete attributes in objects

You can only delete the object's own properties

var obj = {
     name: 'zhang',
     age: 13,
     sayName: function () {
          console.log(this.name);   //zhang
     }
}
// 删除对象中的属性   只能删除对象的自有属性
delete obj.name;
console.log(obj);     //{ age: 13, sayName: [Function: sayName] }

delete obj.sayName     //从obj对象中删除sayName属性
console.log(obj);  //{ age: 13 }

New attributes

obj.newpropname=”value”

var obj = {
     name: 'zhang',
     age: 13,
     sayName: function () {
          console.log(this.name);   //zhang
     }
}
// 新增对象中的属性  
obj.gender = 'male'
console.log(obj);  
// {
//      name: 'zhang',
//      age: 13,
//      sayName: [Function: sayName],
//      gender: 'male'
//    }

Object explicit type conversion (forced type conversion)

  • The three types of mandatory conversions available in ECMAScript are as follows:
Boolean(value): Convert the given value to Boolean
String(value): Convert the given value into a string
Number(value): Convert the given value into a number (can be an integer or floating point number)

* Object type to Boolean type

type of dataValue converted to trueValue converted to false
Booleantruefalse
StringAny non-empty string"" (empty string)
NumberAny non-zero number (including infinity)0 and NaN (not a number)
ObjectAny objectnull
Undefinedwithoutundefined
// 除了空引用(null)会转换为false,其他都被转换为true
var obj = {
  name: "briup",
  age: 13
};
// 使用Boolean包装器进行转换
console.log(Boolean(obj));   //true
console.log(Boolean(!obj));  //false
console.log(Boolean(null));  //false
console.log(Boolean(undefined));   //false
console.log(Boolean(111));  //true 
console.log(Boolean('')); //false
console.log(Boolean(0));  //false
console.log(Boolean(NaN));  //false
console.log(Boolean()); //false
  • Object type to String type
conversion rules :

​ Display conversion is similar to implicit conversion rules, when you want to convert an object to String, similar to the implicit conversion PreferredType is String

​ 1. First call the toString method of the object

​ 2. Determine whether the return value of the method is the basic data type (Number, String, Boolean, Undefined, Null)

​ 3. If the return value is the basic data type, the conversion rule will convert it according to the conversion rule of the corresponding data type

​ 4. If the return value is not a basic data type, continue to call the valueOf method on the basis of the return value

​ 5. Determine whether the return value of valueOf is the basic data type

​ 6. Determine whether it is a basic data type, if it is a basic data type, perform operation 3

​ 7. If it is still not the basic data type, an error will be reported

//直接用toString()方法
var obj = {
     name: 'zhangsan',
     age: 12,
     // 可以重写toString方法,进行我们想要的转换
     toString:function(){
         return this.name+"<-->"+this.age;   //zhangsan<-->12
        
     }
   };
   //两种输出方式
   console.log(obj.toString(), typeof obj.toString());  //zhangsan<-->12 string
   console.log(String(obj), typeof String(obj));  // zhangsan<-->12 string
  • Object type to Number type
conversion rule :

​ Display conversion is similar to implicit conversion rules, when you want to convert the object to Number, similar to the implicit conversion PreferredType is Number

​ 1. Call the valueOf method of the object first

​ 2. Determine whether the return value of the method is the basic data type (Number, String, Boolean, Undefined, Null)

​ 3. If the return value is the basic data type, the conversion rules will convert it according to the conversion rules of the corresponding data type

​ 4. If the return value is not a basic data type, continue to call the toString method on the basis of the return value

​ 5. Determine whether the return value of toString is the basic data type

​ 6. Determine whether it is a basic data type, if it is a basic data type, perform operation 3

​ 7. If it is still not the basic data type, an error will be reported

// Object类型转Number类型

var obj = {
     name: "zhang",
     age: 12,

     //重写toString方法和valueOf方法

     //两个方法都重写了 则调用valueOf()
     valueOf: function () {
          return 20;
     },
     toString: function () {
          return 100;
     },
};
/*
      1.如果只重写了valueOf()或者toString()方法,则调用该方法,并将返回值用Number()转换。
      2.如果两个方法都重写了,则调用valueOf(),并将返回值用Number()转换。
      3.如果两个方法都没有重写,则返回NaN
 */
//    先使用Number 进行转换
//如果两个方法都重写了,则调用valueOf(),并将返回值用Number()转换。
console.log(Number(obj));   //20

detection attributes

Check whether an attribute belongs to an object. There are three commonly used methods:

in

Check whether a property is an object's own property or inherited property

var obj = {
  name: 'zhangsan',
  age: 18,
  school: 'xx大学'
}
//in运算符的左侧为属性名称,右侧为对象
console.log('name' in obj); //true
console.log('age' in obj);  //true
console.log('gender' in obj); //false
//如果用in判断一个属性存在,这个属性不一定是obj的,它可能是obj继承得到的,如:
'toString' in obj;  //  true
////因为toString定义在object对象中,而所有对象最终都会在原型链上指向object,所以obj也拥有toString属性。
Object.prototype.hasOwnProperty()

Check whether the given attribute is the own attribute of the object, and return false for inherited attributes

var obj = {  
name: 'zhangsan',  age: 18,  school: 'xx大学'}console.log(obj.hasOwnProperty('name')); //trueconsole.log(obj.hasOwnProperty('age'));  //trueconsole.log(obj.hasOwnProperty('toString')); //false,toString为继承属性console.log(obj.hasOwnProperty('gender')); //false
Object.prototype.propertyIsEnumerable() ----->> obj.propertyIsEnumerable()

propertyIsEnumerable() is an enhanced version of hasOwnProperty(). In addition to its own properties, it also requires enumerable properties, that is, the properties we create.

var obj = { 
 name: 'zhangsan', 
 age: 18,  
school: 'xx大学'}
console.log(obj.propertyIsEnumerable('name')); //trueconsole.log(obj.propertyIsEnumerable('age'));  //trueconsole.log(obj.propertyIsEnumerable('toString')); //false,不可枚举
console.log(obj.propertyIsEnumerable('gender')); //false

Object prototype properties and methods (prototype methods, methods that can be called by instances)

The properties and methods in the prototype object of the Object constructor can be inherited by the instance of the Object constructor.

Any properties and methods in the Object prototype also exist in other objects, and any object inherits from Object.

image-20210823233826855.png

Summary: Every constructor has a prototype object, the prototype object contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object. ----"JavaScript Advanced Programming"

Commonly used methods in Object prototype:
constructor

​ Save the function of the current object created by the user, and the constructor corresponding to the prototype object

hasOwnProperty(propertyName)

​ Check whether the given attribute name is an object's own attribute

propertyIsEnumerable(propertyName)

​ Check whether the given attribute exists in the current object instance

valueOf()

​ Returns the representation of the object's string, numeric value, and Boolean value

toLocaleString()

​ Returns the string representation of the object, which corresponds to the region of the execution environment

toString()

​ Returns the string representation of the object

isPrototypeOf(object)

​ Check the prototype of the passed object

​ a.isPrototypeOf(b) If a is the prototype of b, it returns true. If b is not an object, or a is not a prototype of b, return false.

// 使用构造函数创建实例对象
var obj = new Object()// 调用原型对象中继承的方法console.log(obj.toString());
console.log(obj.__proto__.toString());// 构造函数 Objectconsole.log(Object);  //[Function: Object]// 原型对象 Object.prototypeconsole.log(Object.prototype);  // {}// 原型对象中的constructor属性  原型对象中的constructor属性指向构造函数console.log(Object.prototype.constructor);  //[Function: Object]console.log(Object === Object.prototype.constructor);  //true// 实例__proto__ 指向 原型对象console.log(obj.__proto__ === Object.prototype);  //true// 创建Date对象var now = new Date();
console.log(now);// 使用原型对象中的方法console.log(now.toString());//Mon Aug 23 2021 23:22:35 GMT+0800 (GMT+08:00) (中国标准时间)
console.log(now.toLocaleString());//2021-8-23 23:22:35

7. In-depth understanding of objects-defining attributes

​ There are two types of attributes in ECMAScript: data attributes and accessor attributes. These two properties are used to set the advanced properties of the property, such as whether the property can be configured, whether it can be read and written, whether it can be traversed, and can monitor data changes through setters and getters.

  • Data attribute characteristics

Data attributes such as name attribute

Contains a property value location, this location can read and write values. The data attribute characteristics are as follows

​ [[ Configurable ]] ----->>Indicates whether to redefine the property by deleting the property, whether to modify the property of the property, or whether to modify the property to an accessor property (the property is directly defined in the object , The default is true). When it is false, it cannot be redefined and cannot be deleted using delete.

​ [[ Enumerable ]]------>> indicates whether the attribute can be returned through a for-in loop. (Properties are directly defined in the object, the default is true)

​ [[ Writable ]] ------>> indicates whether the value of the attribute can be modified. (Properties are directly defined in the object, the default is true)

​ [[ Value ]] ---------->>The data value containing this attribute name:jacky

​ To modify the default properties of attributes, you must use ECMAScript5

Object.defineProperty (the object where the property is located, the name of the property, a descriptor object) method

An object is an unordered collection of multiple key/value pairs. Each attribute in the object can be any type of value.

The definition object can use the form of constructor or literal:

var obj = new Object();
obj.name = 'zhangsan';
obj.say = function () {};

In addition to the above method of adding attributes, you can also use Object.defineProperty define new attributes or modify the original attributes.

Object.defineProperty()

syntax:

Object.defineProperty(obj, prop, descriptor)

parameter description:

  1. obj: required. target
  2. prop: required. The name of the attribute to be defined or modified
  3. descriptor: required. Characteristics of the target attribute

Return value:

The object passed into the function. That is, the first parameter obj;

Object.defineProperty(obj,'name',{   
configurable:true,   
enumerable:true,   
writable:true,   
value:'terry'})
console.log(obj.name); 
Object.defineProperty(obj,"name",{
enumerable:false
})
obj.propertyIsEnumerable("name");//false

Note: When we create an object and set a property for the object, the default properties of the property, Configurable, Enumerable, and Writable, are all true by default, and value is the value of the property.

Object.defineProperties()

Syntax:

Object.defineProperties(obj, props)  

parameter description:

  1. obj: required. target
  2. props: One or more key-value pairs of the object define the specific configuration key-value pairs of the properties that will be added or modified for the object

Return value:

The object passed into the function. That is, the first parameter obj;

var obj = new Object();
Object.defineProperties(obj, {    
name: {        
value: 'zhangsan',        
configurable: false,        
writable: true,        
enumerable: true    
},    
age: {        
value: 18,        
configurable: true    
}})
console.log(obj.name, obj.age) // zhangsan, 18
  • Read properties of attributes

Object.getOwnPropertyDescriptor()

Function:
This method returns the attribute descriptor corresponding to a self-owned attribute on the specified object. (Own attribute refers to the attribute directly assigned to the object, the attribute that does not need to be searched from the prototype chain)

语法: Object.getOwnPropertyDescriptor(obj, prop)

obj: the target object to find
prop: property name in the target object

var person = {    
name: '张三',    
age: 18}
var desc = Object.getOwnPropertyDescriptor(person, 'name'); console.log(desc)  
结果如下// {//     configurable: true,
//     enumerable: true,
//     writable: true,
//     value: "张三"
// }
Object. getOwnPropertyDescriptors()

Function:
Descriptors of all self-attributes of the specified object. If there is no self-attribute, an empty object is returned.

语法: Object.getOwnPropertyDescriptors(obj)

obj: The target object to be found

var person = {    name: '张三',    age: 18}
var desc = Object.getOwnPropertyDescriptors(person);
console.log(desc) //{
//    configurable: true,
//    enumerable: true,
//    value: '张三',
//    writable: true//}
  • Accessor attribute characteristics

Accessor attribute: This attribute does not contain data values, but contains a pair of get and set methods. When reading and writing accessor attributes, these two methods are used for operation and processing.

Four features included in the accessor attribute:

[[Configurable]]------>>Indicates whether the attribute can be redefined by deleting the attribute, whether the property of the attribute can be modified, or whether the attribute can be modified as an accessor attribute, the default is false

[[Enumerable]]------->>Indicates whether the attribute can be returned through a for-in loop, the default is false

[[Get]]-------->>The function called when reading the property, the default value is undefined

[[Set]]-------->>The function called when writing the property, the default value is undefined

​ It should be noted here that the accessor properties cannot be defined directly, they must be defined through the Object.defineProperty() method.

//访问器属性:这个属性不包含数据值,包含的是一对get和set方法,在读写访问器属性时,就是通过这两个方法来进行操作处理的。
var book = {
     _year:2020,  //下划线表示是内部属性,只能通过对象的方法来读写
     editor: 1
}

//访问器属性   Object.defineProperty(obj, prop, descriptor)
// 1. obj:必需。目标对象
// 2. prop:必需。需定义或修改的属性的名字
// 3. descriptor:必需。目标属性所拥有的特性
// 可以使用`Object.defineProperty`定义新属性或修改原有的属性。
Object.defineProperty(book, 'year', {
     // get 函数    如果只写了get方法,当前的year属性就是只读的
     get: function () {
          // 返回私有属性
       return this._year;
     },
     //修改  // 若只指定get方法,不指定set方法,那就默认该属性是只读的
     set:function (newYear) {
          //判断 如果两个值不同 
          if (newYear !== this._year) {
               this._year = newYear;
               this.editor++
          }
     }
})
// 测试访问属性中的get,set方法
console.log('未修改的year:' + book.year);   //未修改的year:2020

book.year = 2023;
console.log('修改后的year:' + book.year);   //修改后的year:2023
console.log('修改year后的editor:' + book.editor);    //修改year后的editor:2

// 访问器属性可以通过Object.getOwnPropertyDescriptor()查询
console.log(Object.getOwnPropertyDescriptor(book, '_year'));   //{ value: 2023, writable: true, enumerable: true, configurable: true }

From this, two-way binding of data can be thought of:

Set a private property in an object (book) (_year: the underscore at the beginning represents the private property), then set the accessor property year for this object (it has not been defined in the object), and trigger the set function when book.year is modified , Through this function, data operations can be performed, such as a series of operations such as data judgment and assignment, so as to realize the two-way binding of data. This principle is the essential principle of vue. Vue is a data-driven framework. When the data changes, the view is automatically updated.

8. Object serialization

Object serialization refers to converting the state of an object into a string, or deserializing it to restore the string to an object function.

RegExp, Error objects, and undefined values ​​cannot be serialized and deserialized.

​ //Issues involving deep copy and shallow copy

JSON.stringify(obj) serializes the object into a JSON string, and can only serialize the enumerable properties of the object

JSON.parse(jsonStr) deserialization

image-20210824003726096.png

var obj = {
     name:'zhang',
     age:14
}

// 对象序列化是指将对象的状态转换为字符串,也可以反序列化,将字符串还原为对象函数
//JSON.stringify(obj) 将对象序列化为JSON字符串,只能序列化对象可枚举的自有属性
var jsonStr = JSON.stringify(obj)

console.log(jsonStr,typeof jsonStr);  //{"name":"zhang","age":14}       string


// JSON.parse(jsonStr) 反序列化   引用地址发生改变
var jsonObj = JSON.parse(jsonStr)

console.log(jsonObj,typeof jsonObj);   //{ name: 'zhang', age: 14 }       object
console.log(obj);    //{ name: 'zhang', age: 14 }  
console.log(jsonObj == obj);   //false

jsonObj.name = 'xxxxx' 
    
console.log(jsonObj);   //{ name: 'xxxxx', age: 14 }    

console.log(obj);

云绮棠兮
48 声望10 粉丝

当野心追赶不上才华,便静下心来努力