【JS】JS基础-对象处理方法整合
对象处理方法工具手册
文章目录
- 1. 对象创建和属性定义
- 创建对象
- 属性定义
- 2. 属性描述符相关 API
- 3. 对象遍历和迭代 API
- 4. 对象复制和合并 API
- 浅拷贝
- 深拷贝
- 5. 对象合并和组合 API
- 6. 原型相关 API
- 7. 对象冻结和密封 API
- 8. 对象比较和转换 API
- 9. 现代 ES6+ 对象 API
- 10. 实用对象操作模式
- 对象解构
- 对象变换
- 11. 高级对象模式
- 工厂模式
- 构造函数模式
- 类语法 (ES6)
1. 对象创建和属性定义
创建对象
// 字面量创建
const obj1 = { name: "John", age: 30 };// 构造函数创建
const obj2 = new Object();
obj2.name = "Jane";// Object.create() - 创建带有原型的对象
const prototypeObj = { greet() { return "Hello"; } };
const obj3 = Object.create(prototypeObj);// Object.fromEntries() - 键值对数组转对象
const entries = [['name', 'Mike'], ['age', 25]];
const obj4 = Object.fromEntries(entries);
属性定义
// Object.defineProperty()
const obj = {};
Object.defineProperty(obj, 'name', {value: 'John',writable: true, // 可写enumerable: true, // 可枚举configurable: true // 可配置
});// Object.defineProperties()
Object.defineProperties(obj, {age: {value: 30,writable: false},email: {value: 'john@example.com',enumerable: true}
});
2. 属性描述符相关 API
const obj = { name: "John", age: 30 };// 获取属性描述符
const desc = Object.getOwnPropertyDescriptor(obj, 'name');
console.log(desc);
// { value: "John", writable: true, enumerable: true, configurable: true }// 获取所有自身属性的描述符
const allDesc = Object.getOwnPropertyDescriptors(obj);// 检查属性是否存在
console.log(obj.hasOwnProperty('name')); // true
console.log(Object.hasOwn(obj, 'name')); // true (ES2022)// 属性枚举状态检查
Object.defineProperty(obj, 'hiddenProp', {value: 'secret',enumerable: false
});
3. 对象遍历和迭代 API
const person = {name: "Alice",age: 28,city: "New York"
};// 获取所有可枚举的自身属性名
const keys = Object.keys(person); // ["name", "age", "city"]// 获取所有可枚举的自身属性值
const values = Object.values(person); // ["Alice", 28, "New York"]// 获取所有可枚举的自身属性键值对
const entries = Object.entries(person);
// [["name", "Alice"], ["age", 28], ["city", "New York"]]// 获取所有自身属性名(包括不可枚举)
const allKeys = Object.getOwnPropertyNames(person);// 获取所有 Symbol 属性
const symbolKeys = Object.getOwnPropertySymbols(person);
4. 对象复制和合并 API
浅拷贝
const original = { a: 1, b: { c: 2 } };// 扩展运算符
const shallowCopy1 = { ...original };// Object.assign()
const shallowCopy2 = Object.assign({}, original);// 注意:浅拷贝只复制第一层,嵌套对象仍是引用
深拷贝
// 简单深拷贝(有限制)
const deepCopy1 = JSON.parse(JSON.stringify(original));// 自定义深拷贝函数
function deepClone(obj) {if (obj === null || typeof obj !== 'object') return obj;if (obj instanceof Date) return new Date(obj);if (obj instanceof Array) return obj.map(item => deepClone(item));const cloned = {};Object.keys(obj).forEach(key => {cloned[key] = deepClone(obj[key]);});return cloned;
}
5. 对象合并和组合 API
const target = { a: 1, b: 2 };
const source1 = { b: 3, c: 4 };
const source2 = { d: 5, e: 6 };// Object.assign() - 合并对象
const merged = Object.assign(target, source1, source2);
// target 被修改为 { a: 1, b: 3, c: 4, d: 5, e: 6 }// 扩展运算符合并
const merged2 = { ...target, ...source1, ...source2 };// 对象组合模式
const behavior1 = { walk() { console.log('walking'); }
};
const behavior2 = { talk() { console.log('talking'); }
};
const person = Object.assign({ name: 'John' }, behavior1, behavior2);
6. 原型相关 API
function Person(name) {this.name = name;
}
Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; };const john = new Person('John');// 获取原型
console.log(Object.getPrototypeOf(john) === Person.prototype); // true// 设置原型
const newProto = { sayGoodbye() { return 'Goodbye'; } };
Object.setPrototypeOf(john, newProto);// 检查原型链
console.log(john instanceof Person); // false (原型已被修改)// 创建带有指定原型的对象
const mike = Object.create(Person.prototype);
Person.call(mike, 'Mike');
7. 对象冻结和密封 API
const obj = { name: "John", age: 30 };// Object.preventExtensions() - 防止添加新属性
Object.preventExtensions(obj);
obj.city = "NY"; // 静默失败或TypeError// Object.isExtensible() - 检查是否可扩展
console.log(Object.isExtensible(obj)); // false// Object.seal() - 密封对象(不能添加/删除属性)
Object.seal(obj);
delete obj.name; // 静默失败
console.log(Object.isSealed(obj)); // true// Object.freeze() - 冻结对象(不能修改)
Object.freeze(obj);
obj.age = 31; // 静默失败
console.log(Object.isFrozen(obj)); // true
8. 对象比较和转换 API
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
const obj3 = obj1;// 引用比较
console.log(obj1 === obj2); // false
console.log(obj1 === obj3); // true// 值比较(自定义函数)
function shallowEqual(obj1, obj2) {const keys1 = Object.keys(obj1);const keys2 = Object.keys(obj2);if (keys1.length !== keys2.length) return false;return keys1.every(key => obj1[key] === obj2[key]);
}// 对象转原始值
const obj = {value: 10,valueOf() { return this.value; },toString() { return `Object with value: ${this.value}`; }
};console.log(obj + 5); // 15 (调用 valueOf)
console.log(String(obj)); // "Object with value: 10"
9. 现代 ES6+ 对象 API
// 属性简写
const name = "John";
const age = 30;
const person = { name, age }; // { name: "John", age: 30 }// 计算属性名
const propName = "firstName";
const dynamicObj = {[propName]: "John",["last" + "Name"]: "Doe"
};// 方法简写
const obj = {// 传统方式traditional: function() { return "traditional"; },// 简写方式shorthand() { return "shorthand"; }
};// Object.hasOwn() - ES2022 (比 hasOwnProperty 更安全)
console.log(Object.hasOwn(person, 'name')); // true
10. 实用对象操作模式
对象解构
const person = { name: "John", age: 30, city: "NY" };// 基本解构
const { name, age } = person;// 重命名
const { name: personName, age: personAge } = person;// 默认值
const { name, country = "USA" } = person;// 嵌套解构
const user = { profile: { firstName: "John", address: { city: "NY" } }
};
const { profile: { firstName, address: { city } } } = user;
对象变换
const users = [{ id: 1, name: "John", active: true },{ id: 2, name: "Jane", active: false }
];// 数组转对象映射
const usersMap = users.reduce((acc, user) => {acc[user.id] = user;return acc;
}, {});// 对象过滤
const activeUsers = Object.fromEntries(Object.entries(usersMap).filter(([id, user]) => user.active)
);// 对象映射
const userNames = Object.fromEntries(Object.entries(usersMap).map(([id, user]) => [id, user.name])
);
11. 高级对象模式
工厂模式
function createUser(name, age) {return {name,age,greet() {return `Hello, I'm ${this.name}`;}};
}
构造函数模式
function User(name, age) {this.name = name;this.age = age;
}User.prototype.greet = function() {return `Hello, I'm ${this.name}`;
};
类语法 (ES6)
class User {constructor(name, age) {this.name = name;this.age = age;}greet() {return `Hello, I'm ${this.name}`;}// 静态方法static createAnonymous() {return new User('Anonymous', 0);}
}
这些 API 覆盖了 JavaScript 对象处理的大部分场景,从基本操作到高级模式都有涉及。