1 overview
Object is the core concept of JavaScript language. It is one of the seven data types, the only complex type and also the most important data type.
What is an object? Simply put, an object is a set of key-value pairs, a kind of unordered composite data set. Such as:
let obj = { 'name': 'frank'.'age'18} :let obj = new Object({'name': 'frank'})
console.log({ 'name': 'frank, 'age18}) ':Copy the code
In the code above, the curly braces define an object, which is assigned to the variable obj, so the variable obj refers to an object. This object contains two internal key-value pairs (also known as two “members”), the first of which is ‘name’:’Hello’, where name is the “key name” (the name of the member) and the string Frank is the “key value” (the value of the member). Key names and key values are separated by colons. The second key-value pair is age: ‘World’, where age is the key name and 18 is the key value. Two key-value pairs are separated by commas. Details:
- Key names are strings, not identifiers, and can contain any character
- Quotation marks can be omitted, after which only identifiers can be written. Even if the quotes are omitted, the key is still a string, which is important.
2 Strange attribute names
If the key is a numeric value, it is automatically converted to a string.
var obj = {
1: 'a'And 3.2:'b',
1e2: true,
1e-2: true,
.234: true,
0xFF: true
};
obj
// Object {
// 1: "a"/ / 3.2:"b", / / 100:true/ / 0.01:true/ / 0.234:true, / / 255:trueKeys (obj) => ["1"."100"."255"."3.2"."0.01"."0.234"]
obj['100'] / /true
Copy the code
Keys (obj) to obtain all keys of obj
In the above code, all of the key names of the object obj, which look like numeric values, are actually automatically converted to strings.
If the key name does not meet the criteria for identifying a name (for example, the first character is a number, or contains a space or operator) and is not a number, it must be quoted; otherwise, an error will be reported.
var obj = {
1p: 'Hello World'}; Var obj = {'1p': 'Hello World'.'h w': 'Hello World'.'p+q': 'Hello World'};Copy the code
The three key names of the object above do not qualify as identifying names, so they must be quoted.
Each key of an object is also called a property. Value is the property value of the object, and its “key value” can be any data type. If the value of an attribute is a function, the attribute is usually called a “method” and can be called like a function.
var obj = {
p: function (x) {
return2 * x; }}; obj.p(1) // 2Copy the code
In the code above, the property P of object obj points to a function.
If the value of the property is still an object, a chained reference is formed.
var o1 = {};
var o2 = { bar: 'hello' };
o1.foo = o2;
o1.foo.bar // "hello"
Copy the code
In the above code, the attribute foo of object O1 refers to object O2, which can be chain-referenced.
The attributes of the object are separated by commas, and the trailing comma may or may not be followed by the last attribute.
var obj = {
p: 123,
m: function() {... }},Copy the code
In the code above, the comma after the m attribute can be used with or without.
Properties can be created dynamically and do not have to be specified at object declaration time.
var obj = {};
obj.foo = 123;
obj.foo // 123
Copy the code
In the code above, assigning the foo property of the obj object directly creates the foo property at run time.
Variable as attribute name
How do you use variables for property names when you’ve always used constants for property names
let p1 = 'name'
let obj = { p1 : 'frank'} write it like this, property name'p1'
let obj = { [p1] : 'frank'} write it like this, property name'name'
Copy the code
Note:
- Attribute names without [] automatically become strings; [] is evaluated as a variable.
- A value that is not a string automatically becomes a string.
Object hidden properties:
- Every object in JS has a hidden property
- This hidden property stores the addresses of objects whose shared properties are made up of
- The object made up of these common attributes is called a stereotype
That is, the hidden property stores the address of the stereotype
Var obj = {} obj. ToString ()Copy the code
Because obj’s hidden property has toString() on it
In addition to strings, symbols can also be property names
let a = Symbol()
let obj = { [a]: 'Hello' }
Copy the code
This is used in “iteration”
3 Object reference
If different variable names refer to the same object, they are all references to that object, that is, to the same memory address. If you change one variable, it affects all the others.
var o1 = {};
var o2 = o1;
o1.a = 1;
o2.a // 1
o2.b = 2;
o1.b // 2
Copy the code
In the code above, o1 and O2 point to the same object, so if you add a property to either variable, the other variable can read and write that property.
In this case, if one variable is removed from the reference to the original object, the other variable is not affected.
var o1 = {};
var o2 = o1;
o1 = 1;
o2 // {}
Copy the code
In the code above, o1 and O2 point to the same object, and then o1 changes to 1, and o2 is still pointing to the same object.
However, this reference is limited to objects if two variables point to a value of the same primitive type. So the variables are all copies of the values.
var x = 1;
var y = x;
x = 2;
y // 1
Copy the code
In the code above, when the value of x changes, the value of y does not change, indicating that y and x do not refer to the same memory address.
4 Expressions or statements?
Objects are represented in braces, which raises the question: if the line begins with a brace, is it an expression or a statement?
{foo: 123} The JavaScript engine reads the above line of code and sees two possible meanings. The first possibility is that this is an expression representing an object that contains a property foo; The second possibility is that this is a statement representing a code block with a tag foo that points to the expression 123.
To avoid this ambiguity, the JavaScript engine’s practice is that if it encounters such a situation, it can’t be determined whether it is an object or a code block, so it is interpreted as a code block.
{ console.log(123) } // 123
Copy the code
The above statement is a code block and can only be executed if interpreted as a code block.
If it is to be interpreted as an object, it is best to enclose parentheses before braces. Because the inside of parentheses can only be expressions, make sure that the braces can only be interpreted as objects.
({foo: 123}) // Correct ({console.log(123)}) // ErrorCopy the code
This difference is most evident in the eval statement, which evaluates a string.
eval('{foo: 123}') / / 123eval('({foo: 123})') // {foo: 123}
Copy the code
In the above code, if there are no parentheses, Eval interprets it as a block of code; With parentheses, it is understood as an object.
5 Attribute operations
5.1 Deleting Attributes
The delete command is used to delete an attribute of an object.
Delete obj. XXX or delete obj[‘ XXX ‘]
Delete the XXX property of obj
Please distinguish between “attribute value undefined” and “without attribute name”.
- Contains no attribute name
‘xxx’ in obj === false
- Contains the attribute name, but the value is undefined
‘xxx’ in obj && obj.xxx === undefined
- Note that obj.xxx === = undefined
Cannot determine whether ‘XXX’ is a property of obj
Analogy: Do you have toilet paper?
A: No // no attribute name
B: Yes, but not with // attribute name, but with undefined value
Programmers should be rigorous, no is no, undefined is undefined.
5.2 Viewing All Properties
View all of its properties
Object.keys(obj)
Copy the code
View self + Common properties
console.dir(obj)
Copy the code
Or print obj. Proto yourself in order with Object.keys
Determine whether an attribute is self-contained or common
obj.hasOwnProperty('toString')
Copy the code
The prototype
Every object has a prototype
- The stereotype holds the common properties of the object
For example, the prototype of obj is an object, obj.__proto__, which holds the address of the object and has properties like toString/constructor/valueOf
- The prototype of an object is also an object
So the prototype of an object has a prototype and the prototype of obj = {} is the prototype of all objects and the prototype contains the common property of all objects, which is the root of the object and the prototype also has a prototype, which is NULL
There are two ways to view properties:
Point syntax: obj.key
Parenthesis syntax: obj[‘key’]
Obj [key] // The value of the variable key is not ‘key’.
- Use bracket syntax in preference
Dot syntax will trick you into thinking key isn’t a string until you’re sure you can’t confuse the two
- Obj. Name = obj[‘name’]
- Obj. Name is not the same as obj[name] simply put, name is a string, not a variable.
Let name = ‘frank’ obj[name] is equivalent to obj[‘frank’] instead of obj[‘name’] and obj.name
code
let list = ['name'.'age'.'gender']
let person = {
name:'frank', age:18, gender:'man'}
for(let i = 0; i < list.length; i++){
let name = list[i]
console.log(person__???__)
}
Copy the code
Causes all the attributes of Person to be printed
Options:
console.log(person.name)
console.log(person[name])
5.3 Modifying or Adding Attributes
Direct assignment
let obj = {name: 'frank'} // name is the string obj.name ='frank'// name is the string obj['name'] = 'frank'
obj[name] = 'frank'// error: obj['na'+'me'] = 'frank'
let key = 'name'; obj[key] = 'frank'
let key = 'name'; obj.key = 'frank'// error because obj. Key = obj['key']
Copy the code
Batch assignment
Object.assign(obj, {age: 18, gender: 'man'})
Copy the code
Modify or add a common property
Common attributes cannot be modified or added by themselves
letObj = {}, obj2 = {} // toString obj.toString ='xxx'Will only change the obj2. ToString property of obj itself, again on the prototypeCopy the code
To modify or add attributes to the prototype:
obj.__proto__.toString = 'xxx'/ / do not recommend using __proto__ Object. The prototype. ToString ='xxx'
Copy the code
In general, don’t modify a prototype, it can cause a lot of problems
Modifying hidden attributes
Proto is not recommended
let obj = {name:'frank'}
let obj2 = {name: 'jack'}
let common = {kind: 'human'}
obj.__proto__ = common
obj2.__proto__ = common
Copy the code
Object. Create is recommended
let obj = Object.create(common)
obj.name = 'frank'
let obj2 = Object.create(common)
obj2.name = 'jack'
Copy the code
Norms basically mean, if you want to change, change at the beginning, don’t change later