js实现属性
实现属性的方法
在JavaScript中,可以通过多种方式实现对象的属性。以下是几种常见的方法:
使用字面量定义属性
通过对象字面量直接定义属性:
const obj = {
name: 'John',
age: 30
};
使用点符号添加属性
通过点符号动态添加属性:
const obj = {};
obj.name = 'John';
obj.age = 30;
使用方括号添加属性
通过方括号动态添加属性,适用于属性名需要计算的情况:
const obj = {};
const propName = 'name';
obj[propName] = 'John';
obj['age'] = 30;
使用Object.defineProperty
通过Object.defineProperty定义属性,可以控制属性的特性(如可枚举、可配置、可写等):
const obj = {};
Object.defineProperty(obj, 'name', {
value: 'John',
writable: true,
enumerable: true,
configurable: true
});
使用Object.defineProperties
通过Object.defineProperties一次性定义多个属性:

const obj = {};
Object.defineProperties(obj, {
name: {
value: 'John',
writable: true
},
age: {
value: 30,
writable: false
}
});
使用类定义属性
在类中定义属性:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person = new Person('John', 30);
使用getter和setter
通过getter和setter定义属性,可以在访问或修改属性时执行自定义逻辑:
const obj = {
_name: 'John',
get name() {
return this._name;
},
set name(value) {
this._name = value;
}
};
属性特性
每个属性都有以下特性:
value:属性的值writable:是否可写enumerable:是否可枚举configurable:是否可配置
可以通过Object.getOwnPropertyDescriptor获取属性的特性:

const descriptor = Object.getOwnPropertyDescriptor(obj, 'name');
console.log(descriptor);
动态属性名
ES6支持计算属性名,可以在对象字面量中使用表达式作为属性名:
const propName = 'name';
const obj = {
[propName]: 'John'
};
删除属性
使用delete操作符删除属性:
delete obj.name;
检查属性是否存在
使用in操作符或hasOwnProperty方法检查属性是否存在:
console.log('name' in obj);
console.log(obj.hasOwnProperty('name'));
遍历属性
使用for...in循环或Object.keys方法遍历属性:
for (const key in obj) {
console.log(key, obj[key]);
}
console.log(Object.keys(obj));






