概念
键值对的集合,用于表示复杂数据结构
内容
属性:描述对象特征的值(原始类型或其他对象)
方法:对象能够执行的操作(函数类型的属性)
创建方式
1:字面量创建
const user = {
username: 'codeMaster',
age: 28, isAdmin: false,
login: function () { console.log(`${this.username} 登录成功`); }
};
2:构造函数创建
function Book(title, author, price) {
this.title = title;
this.author = author;
this.price = price;
this.getInfo = function () {
return `${this.title} - ${this.author} [¥${this.price}]`;
};
}
const jsBook = new Book('JS高级编程', 'Nicholas C.Zakas', 99);
3: Object.create() 创建
const parentObj = { type: 'parent' };
const childObj = Object.create(parentObj, {
name: { value: 'child' },
age: { value: 2 }
});
对象属性深度操作
1:属性访问
console.log(jsBook.title);
const propName = 'author';
console.log(jsBook[propName]);
2:属性修改/添加
jsBook.publisher = '人民邮电出版社';
jsBook['publishYear'] = 2023;
jsBook.discount = function (percent) {
return this.price * (1 - percent);
};
3:属性删除
delete jsBook.publishYear;
4:属性检测
console.log('price' in jsBook);
console.log(jsBook.hasOwnProperty('author'));
5:属性遍历
for (let key in jsBook) {
if (jsBook.hasOwnProperty(key)) {
console.log(`${key}: ${jsBook[key]}`);
}
}
方法
const calculator = {
PI: 3.1415926,
add: function (a, b) { return a + b },
multiply(a, b) {
return a * b;
},
badThisExample: () => {
console.log(this);
}
}
特性
1: 原型系统
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function () {
console.log(`${this.name} 发出声音`);
};
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
bark() { console.log('汪汪!'); }
}
const myDog = new Dog('阿黄', '中华田园犬');
2:属性描述符
const obj = {};
Object.defineProperty(obj, 'readOnlyProp', {
value: 42,
writable: false,
enumerable: true,
configurable: false
});
3:对象冻结
const constObj = { PI: 3.14159 };
Object.freeze(constObj);
constObj.PI = 3.14;
常用对象操作
1:合并
const defaults = { color: 'red', size: 'medium' };
const userSettings = { size: 'large', darkMode: true };
const merged = Object.assign({}, defaults, userSettings);
2:解构
const { brand, model, specifications: { battery } } = smartphone;
console.log(`${brand} ${model} 电池容量: ${battery}`);
3:JSON转换
const jsonStr = JSON.stringify(jsBook);
const jsonStr = JSON.stringify(jsBook);
实践与注意
1:对象引用特性
const objA = { value: 1 };
const objB = objA;
objB.value = 2;
console.log(objA.value);
2:深浅拷贝选择
Object.assign() 执行浅拷贝
深拷贝建议使用 JSON.parse(JSON.stringify(obj)) 或工具库
3:原型链污染防范
Object.prototype.customMethod = function() {};
const safeObj = Object.create(null);
4:属性存在性检查
if (obj.someProp) { }
if ('someProp' in obj) { }