前端技巧第六期JavaScript对象

概念

键值对的集合,用于表示复杂数据结构
内容
属性:描述对象特征的值(原始类型或其他对象)
方法:对象能够执行的操作(函数类型的属性)

创建方式

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); // true
console.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 jsonStr = JSON.stringify(jsBook);

实践与注意

1:对象引用特性
const objA = { value: 1 };
const objB = objA;
objB.value = 2;
console.log(objA.value); // 2(注意引用关系)
2:深浅拷贝选择
Object.assign() 执行浅拷贝
深拷贝建议使用 JSON.parse(JSON.stringify(obj)) 或工具库
3:原型链污染防范
// 不安全的操作
Object.prototype.customMethod = function() {};
// 安全创建纯净对象
const safeObj = Object.create(null);
4:属性存在性检查
// 错误方式
if (obj.someProp) { /* 可能误判false值 */ }
// 正确方式
if ('someProp' in obj) { /* ... */ }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值