Sorting out javascript object knowledge points

Posted by simshaun on Thu, 03 Mar 2022 08:25:11 +0100

Article reference

https://www.w3school.com.cn/js/js_object_definition.asp

JavaScript object definition

In js, almost everything is an object:
Booleans are objects (if defined with the new keyword)
Numbers are objects (if defined with the new keyword)
A string is an object (if defined with the new keyword)
Dates are always objects
Arithmetic is always an object
Regular expressions are always objects
Arrays are always objects
Functions are always objects
Objects are always objects
All JavaScript values, except the original values, are objects.

#JavaScript raw value
Raw values are values that have no properties or methods.
The original data type refers to the data that has the original value.
JavaScript defines five types of raw data:
string
number
boolean
null
undefined
The original values are immutable (they are hard coded and therefore cannot be changed).
Assuming x = 3.14, you can change the value of X. However, you cannot change the value of 3.14.
Creating JavaScript objects
1. Use object literal to create, define and create a single object, and use object text

var person = {
    firstName:"Bill",
    lastName:"Gates",
    age:62,
    eyeColor:"blue"
};

2. Define and create a single object through the keyword new

var person = new Object();
person.firstName = "Bill";
person.lastName = "Gates";
person.age = 50;
person.eyeColor = "blue"; 

3. Define an object constructor, and then create an object of construction type.
JavaScript objects are mutable
JavaScript objects are addressed by reference, not by value

var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"}
var x = person;
x.age = 10;           // This will change both x.age and person age

JavaScript object properties

Property refers to the value associated with the JavaScript object.
JavaScript objects are collections of unordered attributes.
Properties can usually be modified, added, and deleted, but some properties are read-only.
The methods to access object properties are

//1
objectName.property           // person.age
//example
person.firstname + " is " + person.age + " years old.";
//2
objectName["property"]       // person["age"]
//example
person["firstname"] + " is " + person["age"] + " years old.";
//3
//The expression must evaluate to a property name.
objectName[expression]       // x = "age"; person[x]
//example
let x="firstname",y="age"
`${person[x]} is ${person[y]} years old.`;

JavaScript for... in loop

for (variable in object) {
    //Code to execute
}
//example
var person = {fname:"Bill", lname:"Gates", age:62}; 
//You must use person[x] in the loop.
//person.x will not work (because x is a variable).
for (x in person) {
    txt += person[x];
}

Add new attribute
Adding new attributes by assignment

person.nationality = "English";

Add through the defineProperty method of the Object object

Object.defineProperty(person,'nationality',{value:'English'})

Delete attribute
Delete keyword to delete an attribute from an object:

var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"};
delete person.age;   // Or delete person["age"];

be careful:
1. The delete keyword will delete both the value of the attribute and the attribute itself.
2. After deletion, the attribute cannot be used until it is added back.
3. The delete operator is designed for object properties. It has no effect on variables or functions.
4. The delete operator should not be used for predefined JavaScript object attributes. Doing so will crash the application.
5.delete keyword will not delete inherited attributes, but if you delete a prototype attribute, it will affect all objects inherited from the prototype.

JavaScript display object

Direct output object will output [object Object]

const person = {
  name: "Bill",
  age: 19,
  city: "Seattle"
};

document.getElementById("demo").innerHTML = person;//[object Object]

terms of settlement:
1. Display object properties by name
2. Use circular display object attributes
Use object 3 Values () converts property values into arrays to display objects
4. Use JSON stringify()
1. Display object properties by name

const person = {
  name: "Bill",
  age: 19,
  city: "Seattle"
};
document.getElementById("demo").innerHTML =
person.name + "," + person.age + "," + person.city;

2. Use a loop to display object properties

const person = {
  name: "Bill",
  age: 19,
  city: "Seattle"
};
let text=""
for(let x in person)
{
	text+=person[x]
}
document.getElementById("demo").innerHTML =x //Bill19Seattle

3. Use object values()
By using object Values(), any JavaScript object can be converted into an array:

const person = {
  name: "Bill",
  age: 19,
  city: "Seattle"
};

const myArray = Object.values(person); //['Bill', 19, 'Seattle']

4. Use JSON stringify()

//Functions are not crosstalk
const person = {
  name: "Bill",
  age: 19,
  city: "Seattle"
  age: function () {return 19;}
};
let myString = JSON.stringify(person);//'{"name":"Bill","age":19,"city":"Seattle"}'

const arr = ["John", "Peter", "Sally", "Jane"];
let myString = JSON.stringify(arr);//'["John","Peter","Sally","Jane"]'

JavaScript object accessors (Getter and Setter)

Getter and Setter allow you to define object accessors (properties to be evaluated).
JavaScript Getter (get keyword)
Use the lang attribute to get the value of the language attribute.

const person = {
  name: "Bill",
  age: 19,
  city: "Seattle",
  language:"Chinese",
  get lang(){
  	return this.language
  }
};
person.lang //"Chinese"

JavaScript Setter (set keyword)
Use the lang attribute to set the value of the language attribute.

const person = {
  name: "Bill",
  age: 19,
  city: "Seattle",
  language:"Chinese",
  //Use set keyword
  set lang(lang){
  	this.language=lang
  },
  //Create method
  setLang:function(lang){
  	this.language=lang
  }
};
//Use set keyword
person.lang ="en";
//Use the method to change the value of language
person.setLang('ch')

Using getter and setter has advantages over using object methods to obtain and modify object properties
1. More concise syntax is provided
2. Conducive to background work
3. It allows the syntax of attributes and methods to be the same
4. Conducive to background work
Object. The defineproperty() method can also be used to add getters and setters:

// Define object
var obj = {counter : 0};

// Define setters
Object.defineProperty(obj, "reset", {
  get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
  get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
  get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
  set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
  set : function (value) {this.counter -= value;}
});

// Operation counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;

JavaScript object constructor

The function name of the constructor should be capitalized
Create constructor

function Person(name,age,sex)
{
	this.name=name
	this.age=age
	this.sex=sex
}
let father=new Person('chapter',52,'male') //Person {name: 'chapter', age: 52, sex: 'male'}
//Adding properties to an object
father.height=162
//Add a method to the object. Ordinary functions in the object cannot use arrow functions, or they will point to window
father.addAge=function (){
	this.age=this.age+1
}
//When using function nesting, this in the inner function points to the window object, which is solved by using the arrow function

father.getAge=function(){
	/*var getFatherAge=()=>{
		return this.age
	}
	return getFatherAge()*/
	//Use immediate function
	return (()=>{
		return this.age
	})()
}
father.addAge() //age=52
father.getAge() //age=53

//Cannot add new properties and methods to an existing constructor
Person.nationality = "English";

this keyword
In JavaScript, something called this is the "owner" of the code.
The value of this, when used in an object, is the object itself.
In the constructor function, this has no value. It is a substitute for new objects. When a new object is created, the value of this will become the new object.
Note that this is not a variable. It is a keyword. You cannot change the value of this.
Arrow function
/The arrow function does not have its own this value. The this used in the arrow function comes from the function scope chain. Its value follows the same rules as ordinary variables and looks up layer by layer in the function scope chain.
//You need to use object The function called by method () should be defined by ordinary function instead of arrow function. The value of this used in the object method has a definite meaning, which refers to the object itself.
//In other cases, all arrow functions are used.
reference resources

https://www.cnblogs.com/xxcn/p/11056495.html

Built in JavaScript constructor

//The Math() object no longer this column. Math is a global object. The new keyword is not available for math.
var x1 = new Object();    // A new Object var x1 = {}; 
var x2 = new String();    // A new String object var x2 = "";
var x3 = new Number();    // A new Number object var x3 = 0;
var x4 = new Boolean();   // A new Boolean object var x4 = false; 
var x5 = new Array();     // A new Array object var x5 = [];
var x6 = new RegExp();    // A new RegExp object var x6 = / () /;
var x7 = new Function();  // A new Function object var x7 = function() {}
var x8 = new Date();      // A new Date object

Due to performance considerations, try to use literal quantity

JavaScript object prototype

All JavaScript objects inherit properties and methods from the prototype.
Prototype inheritance
All JavaScript objects inherit properties and methods from the prototype.
Date object inherits from date prototype. Array objects inherit from array prototype. The Person object inherits from Person prototype.
Object.prototype is at the top of the prototype inheritance chain:
Date objects, array objects, and Person objects all inherit from object prototype.
Use the prototype property to add methods and properties of the object constructor

	function Person(name,age,sex)
	{
		this.name=name
		this.age=age
		this.sex=sex
	}
	let mother = new  Person('Zhang',51,'female')
	//Adding attributes using prototype
	Person.prototype.language='chinese'
	//Adding methods using prototype
	Person.prototype.getLanguage=function(){
		return this.language
	}
	mother.language  //chinese
	mother.getLanguage() //chinese

JavaScript object method


const person = {
  firstName:"Bill", 
  lastName:"Gates",
  age: 19,
  city: "Seattle",
  language:"Chinese",
  get lang(){
  	return this.language
  }
};
//Use the Object object to modify the value of the person Object
Object.defineProperty(person,"language",{value:'English'})
// Add attribute
Object.defineProperty(person, "year", {value:"2008"});
//Add Getter and Setter
Object.defineProperty(person, "fullName", {
  get: function () {return this.firstName + " " + this.lastName;}
});

Change metadata

Map object

The Map object has key value pairs, and the key can be any data type.
The Map object remembers the original insertion order of keys.
The Map object has an attribute that represents the size of the Map.

// create object
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};

// Create a new Map
const fruits = new Map();

// Add new Elements to the Map
fruits.set(apples, 500);
fruits.set(bananas, 300);
fruits.set(oranges, 200);

//Pass Array to the new Map() constructor:
// return
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};

// Create a new Map
const fruits = new Map([
  [apples, 500],
  [bananas, 300],
  [oranges, 200]
]);
fruits.get(apples);    // Return 500
//Map.size returns the number of elements in the map:
fruits.size; //3
//Map.delete() to delete a map element:
fruits.delete(apples);
//Map.clear() removes all elements from the map:
fruits.clear();
///If a key exists in the Map, the Map Has() returns true;
fruits.has(apples);



Set object

Definition: Set is a Set of unique values. Each value can only appear once in the Set. At the same time, Set can accommodate any value of any data type.
Create Set variable:

// Create a new Set
const letters = new Set(["a","b","c"]);
typeof letters;      // Return object.
letters instanceof Set;  // Return true
letters.add("d");
letters.add("e");
//If you add an equivalent element, only the first element is saved:

Methods and properties of Set object

Topics: C Front-end npm html