管理

(转载)20个JavaScript重点知识点(3)对象

Posted on 2025-05-22 10:45  lzhdim  阅读(10034)  评论(0)    收藏  举报

对象基础概念

 JavaScript 对象是键值对的集合,用于表示复杂数据结构。每个对象可以包含:

  • 属性:描述对象特征的值(原始类型或其他对象)

  • 方法:对象能够执行的操作(函数类型的属性)

// 典型对象示例const smartphone = {  brand: 'Xiaomi',  model: '14 Ultra',  price: 6499,  launchYear: 2024,  checkAvailability: function() {    return this.stock > 0 ? '有货' : '缺货';  },  specifications: {    display: '6.8英寸 AMOLED',    storage: '512GB',    battery: '5300mAh'  }};

对象创建方式

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); // "JS高级编程"
// 括号表示法(支持动态属性名)const propName = 'author';console.log(jsBook[propName]); // "Nicholas C.Zakas"

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); // trueconsole.log(jsBook.hasOwnProperty('author')); // true

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) { // ES6简写语法    return a * b;  },  // 箭头函数中的this问题需注意  badThisExample: () => {    console.log(this); // 指向外层this(可能不是预期结果)  }};

高级对象特性

1. 原型系统

function Animal(name) {  this.name = name;}
Animal.prototype.speak = function() {  console.log(`${this.name} 发出声音`);};
class Dog extends Animal { // ES6 class语法  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);// { color: 'red', size: 'large', darkMode: true }

2. 对象解构

const { brand, model, specifications: { battery } } = smartphone;console.log(`${brand} ${model} 电池容量: ${battery}`);

3. JSON转换

const jsonStr = JSON.stringify(jsBook);const parsedObj = JSON.parse(jsonStr);

实际开发常见应用场景

1. 配置管理

const appConfig = {  apiBaseUrl: 'https://api.example.com/v2',  maxRetries: 3,  timeout: 5000,  featureFlags: {    newUI: true,    darkMode: false  }};

2. 函数参数处理

function createUser({ name, email, age = 18, isAdmin = false }) {  // 参数处理逻辑}
createUser({   name: '李小明',   email: 'lxm@example.com' });

3. 模块化开发

// module.jsexport const utils = {  formatDate(date) { /* ... */ },  debounce(fn, delay) { /* ... */ },  deepClone(obj) { /* ... */ }};
// app.jsimport { utils } from './module.js';

最佳实践与注意点

 1.对象引用特性

const objA = { value: 1 };const objB = objA;objB.value = 2;console.log(objA.value); // 2(注意引用关系)
  1. 2.深浅拷贝选择

  • Object.assign() 执行浅拷贝

  • 深拷贝建议使用 JSON.parse(JSON.stringify(obj)) 或工具库

  1. 3.原型链污染防范

    // 不安全的操作Object.prototype.customMethod = function() {};
    // 安全创建纯净对象const safeObj = Object.create(null);

4.属性存在性检查:

// 错误方式if (obj.someProp) { /* 可能误判false值 */ }
// 正确方式if ('someProp' in obj) { /* ... */ }
Copyright © 2000-2022 Lzhdim Technology Software All Rights Reserved