object
concept
What is an object? Simply put, an object is a set of key-value pairs, a kind of unordered composite data set.
var obj = {
foo: 'Hello'.bar: 'World'
};
Copy the code
The curly braces define an object, which is assigned to the variable obj, so the variable obj refers to an object. The object contains two internal key-value pairs (also known as two “members”), the first of which is foo: ‘Hello’, where foo is the “key name” (the name of the member) and the string Hello is the “key value” (the value of the member). Key names and key values are separated by colons. The second key-value pair is bar: ‘World’, where bar is the key name and World is the key value. Two key-value pairs are separated by commas.
How objects are created
The new Object () method
var person1 = new Object(a);// create a new empty object
person1.name = "jimmy";
Copy the code
Literal mode
var obj = {
name:'jimmy'
}
Copy the code
The factory method
function createPerson(name,age){
// Create an empty object
var person = new Object(a);// Add attributes and methods that can accept parameter values
person.name = name;
person.age = age;
// Use the object as the return value of the function
return person;
}
// To create an object, call the factory function
var p1 = createPerson("jimmy".18);
Copy the code
The constructor
function Person(name,age){
this.name = name;
this.age = age;
this.sayHi = function () {
console.log("hello");
};
}
var p = new Person("jimmy".18);
Copy the code
Key name
All keys of an object are strings (ES6 introduces the Symbol value as a key), so you can use quotes or not. The above code could also be written as follows.
var obj = {
'foo': 'Hello'.'bar': 'World'
};
Copy the code
If the key is a numeric value, it is automatically converted to a string.
var obj ={
100:"jimmy"
}
obj['100'] // jimmy
Copy the code
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.
/ / an error
var obj = {
1p: 'Hello World'
};
/ / is not an error
var obj = {
'1p': 'Hello World'.'h w': 'Hello World'.'p+q': 'Hello World'
};
Copy the code
Each key name of an object is also called a property, 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) {
return 2* x; }}; obj.p(1) / / 2
Copy 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
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
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.
Expression or statement
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 }
Copy the code
When a JavaScript engine reads the above line of code, it will see that there are 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 }) / / right
({ console.log(123)})/ / an error
Copy the code
Operations on properties
Property reading
There are two ways to read the properties of an object, one using the dot operator and the other using the square bracket operator.
var obj = {
p: 'Hello World'
};
obj.p // "Hello World"
obj['p'] // "Hello World"
Copy the code
The above code uses the dot operator and the square bracket operator respectively to read the property P.
Note that if you use the square bracket operator, the key name must be enclosed in quotes or it will be treated as a variable.
var foo = 'bar';
var obj = {
foo: 1.bar: 2
};
obj.foo / / 1
obj[foo] / / 2
Copy the code
In the above code, foo is a string if the dot operator is used to refer to the foo property of obj. If the square bracket operator is used, but no quotes are used, then foo is a variable pointing to the string bar.
Expressions can also be used inside the square bracket operators.
obj['hello' + ' world']
obj[3 + 3]
Copy the code
Numeric keys can be unquoted because they are automatically converted to strings.
var obj = {
0.7: 'Hello World'
};
obj['0.7'] // "Hello World"
obj[0.7] // "Hello World"
Copy the code
Note that numeric keys cannot use dot operators (because they are treated as decimal points), only square brackets operators.
var obj = {
123: 'hello world'
};
obj123. / / an error
obj[123] // "hello world"
Copy the code
Viewing properties
To view all the properties of an Object itself, use the object.keys method.
var obj = {
key1: 1.key2: 2
};
Object.keys(obj);
// ['key1', 'key2']
Copy the code
Attribute deletion
The delete command is used to delete an attribute of an object.
var obj = { p: 1 };
Object.keys(obj) // ["p"]
delete obj.p // true
obj.p // undefined
Object.keys(obj) / / []
Copy the code
In the code above, the delete command removes the p property of the object obj. After deletion, reading the p property returns undefined, and the return value of the object. keys method no longer includes the property.
Note that if you delete a nonexistent property, delete does not report an error and returns true.
var obj = {};
delete obj.p // true
Copy the code
In the above code, the object obj does not have a p attribute, but the delete command returns true. Therefore, an attribute cannot be assumed to exist based on the result of the delete command.
The delete command returns false in only one case, if the property exists and cannot be deleted. The delete command can only delete attributes of the object itself, but cannot delete inherited attributes
var obj = {};
delete obj.toString // true
obj.toString // function toString() { [native code] }
Copy the code
In the code above, toString is an inherited property of obj. The delete command returns true, but the property is not deleted. This example also shows that even if delete returns true, the value of this property can still be read.
Attribute exists: in operator
The in operator is used to check whether an object contains an attribute (note that it checks the key name, not the value) and returns true if it does, false otherwise. It has a string on the left, representing the property name, and an object on the right.
var obj = { p: 1 };
'p' in obj // true
'toString' in obj // true
Copy the code
One problem with the IN operator is that it does not recognize which attributes belong to the object itself and which are inherited. As in the code above, the object obj itself does not have a toString attribute, but the in operator returns true because the attribute is inherited.
In this case, you can use the object’s hasOwnProperty method to determine whether it is a property of the object itself.
var obj = {};
if ('toString' in obj) {
console.log(obj.hasOwnProperty('toString')) // false
}
Copy the code
Property traversal
for… The in loop is used to iterate over all properties of an object.
var obj = {a: 1.b: 2.c: 3};
for (var i in obj) {
console.log('key name:', i);
console.log('Key:', obj[i]);
}
// key name: a
// Key: 1
// key name: b
// Key: 2
// key name: c
// Key: 3
Copy the code
for… There are two usage considerations for the in loop.
- It iterates over all of the object’s enumerable properties and skips those that are not.
- It traverses not only the properties of the object itself, but also the inherited properties.
For example, objects inherit the toString attribute, but for… The in loop does not traverse this property.
var obj = {};
// The toString attribute exists
obj.toString // toString() { [native code] }
for (var p in obj) {
console.log(p);
} // There is no output
Copy the code
In the code above, the object obj inherits the toString attribute, which is not used by the for… The in loop iterates through to because it is “non-traversal” by default.
If the inherited property is traversable, it will be for… In loops through to. In general, however, you just want to iterate over the properties of the object itself, so use for… In, you should use the hasOwnProperty method inside the loop to determine if a property is a property of the object itself.
var person = { name: 'Lao zhang' };
for (var key in person) {
if (person.hasOwnProperty(key)) {
console.log(key); }}// name
Copy the code