Object basics
In JavaScript, objects are a composite data type used to store collections of key-value pairs. They are not only a core concept of the language but also provide a flexible way to organize and manipulate data. Understanding the fundamental characteristics of objects is crucial for writing efficient code.
Basic Structure of Objects
Objects consist of properties and methods. Properties are key-value pairs, where the keys are typically strings or Symbols, and the values can be of any data type. Methods are properties of function type. Object literals are the most common way to create objects:
const person = {
name: 'Zhang San',
age: 30,
greet: function() {
console.log(`Hello, I am ${this.name}`);
}
};
Properties can be accessed using dot notation or square brackets:
console.log(person.name); // "Zhang San"
console.log(person['age']); // 30
person.greet(); // Call the method
Dynamic Property Operations
JavaScript allows dynamically adding or deleting properties at runtime:
// Add a new property
person.job = 'Engineer';
// Delete a property
delete person.age;
// Check property existence
'name' in person; // true
Use Object.keys()
to get all enumerable properties:
const keys = Object.keys(person); // ["name", "greet", "job"]
Constructors and Instances
Constructors can be used to create multiple similar objects:
function Book(title, author) {
this.title = title;
this.author = author;
this.getInfo = function() {
return `${this.title} - ${this.author}`;
};
}
const book1 = new Book('JavaScript Advanced Programming', 'Nicholas');
console.log(book1.getInfo());
Prototype Inheritance Mechanism
Every JavaScript object has a prototype chain for inheritance:
Book.prototype.discount = function(percent) {
return `This book has a ${percent}% discount`;
};
console.log(book1.discount(20)); // Call the prototype method
Use Object.create()
to explicitly set the prototype:
const animal = { eats: true };
const rabbit = Object.create(animal);
console.log(rabbit.eats); // true
Object Destructuring Assignment
ES6 introduced destructuring syntax to simplify property extraction:
const { name, job } = person;
console.log(name, job); // "Zhang San" "Engineer"
// Nested destructuring
const user = {
id: 1,
profile: {
name: 'Li Si',
address: 'Beijing'
}
};
const { profile: { address } } = user;
console.log(address); // "Beijing"
Object Property Descriptors
Property descriptors control property behavior:
Object.defineProperty(person, 'gender', {
value: 'male',
writable: false, // Not writable
enumerable: true // Enumerable
});
// Attempting to modify will silently fail (throws an error in strict mode)
person.gender = 'female';
console.log(person.gender); // Still "male"
Get the full descriptor:
const desc = Object.getOwnPropertyDescriptor(person, 'name');
/*
{
value: "Zhang San",
writable: true,
enumerable: true,
configurable: true
}
*/
Object Freezing and Sealing
JavaScript provides three ways to restrict object modification:
const obj = { prop: 42 };
// 1. Prevent extensions
Object.preventExtensions(obj);
obj.newProp = 'test'; // Silently fails
// 2. Seal object (cannot add/delete properties)
Object.seal(obj);
delete obj.prop; // Silently fails
// 3. Freeze object (completely immutable)
Object.freeze(obj);
obj.prop = 999; // Silently fails
ES6 Class Syntax Sugar
The class
syntax provides a clearer way to write object-oriented code:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter method
get area() {
return this.calcArea();
}
// Instance method
calcArea() {
return this.height * this.width;
}
// Static method
static createSquare(side) {
return new Rectangle(side, side);
}
}
const rect = new Rectangle(10, 5);
console.log(rect.area); // 50
const square = Rectangle.createSquare(10);
Object Iteration Methods
ES6 introduced multiple ways to iterate over objects:
const scores = { math: 90, science: 85, history: 88 };
// 1. Object.keys()
for (const key of Object.keys(scores)) {
console.log(key);
}
// 2. Object.values()
console.log(Object.values(scores)); // [90, 85, 88]
// 3. Object.entries()
for (const [subject, score] of Object.entries(scores)) {
console.log(`${subject}: ${score}`);
}
Deep Copy vs. Shallow Copy
Object copying requires special attention to references:
// Shallow copy
const original = { a: 1, b: { c: 2 } };
const shallowCopy = Object.assign({}, original);
shallowCopy.b.c = 99;
console.log(original.b.c); // 99 (modified)
// Deep copy solution
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.b.c = 100;
console.log(original.b.c); // Still 99
Objects vs. Maps
ES6's Map is more suitable than objects in certain scenarios:
const map = new Map();
map.set('name', 'Wang Wu');
map.set(1, 'Numeric key');
map.set({}, 'Object as key');
console.log(map.get(1)); // "Numeric key"
console.log(map.size); // 3
// Object keys are not converted to strings
const objKey = {};
map.set(objKey, 'Special object');
console.log(map.get({})); // undefined (different reference)
console.log(map.get(objKey)); // "Special object"
Optional Chaining Operator
ES2020's optional chaining simplifies deep property access:
const company = {
name: 'TechCorp',
departments: {
dev: { size: 50 },
hr: { size: 10 }
}
};
// Traditional way
const devSize = company.departments && company.departments.dev && company.departments.dev.size;
// Optional chaining way
const modernDevSize = company.departments?.dev?.size;
console.log(modernDevSize); // 50
// Non-existent properties return undefined
const salesSize = company.departments?.sales?.size;
console.log(salesSize); // undefined
Nullish Coalescing Operator
A logical operator that works well with optional chaining:
const config = {
timeout: 0,
title: '',
animation: null
};
// Traditional default value setting
const timeout = config.timeout !== undefined ? config.timeout : 1000;
// Nullish coalescing operator
const modernTimeout = config.timeout ?? 1000;
const title = config.title ?? 'Default Title';
const animation = config.animation ?? 'fade';
console.log(modernTimeout); // 0 (0 is not null/undefined)
console.log(title); // "" (empty string is not null/undefined)
console.log(animation); // "fade"
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn