Object Properties
Managing JavaScript Object Properties
JavaScript offers a variety of methods to manipulate object properties. These include adding new properties, changing existing ones, and configuring property attributes like visibility, writability, and configurability.
Adding or Changing Object Properties
Object.defineProperty()
- This method allows you to add a new property to an object or modify attributes of an existing property.
Adding a New Property:
const person = { firstName: "John", lastName: "Doe", language: "EN"};
Object.defineProperty(person, "year", { value: "2008" });
Modifying an Existing Property:
Object.defineProperty(person, "language", { value: "NO" });
Property Attributes:
- writable: If true, the property's value can be changed.
- enumerable: If true, the property will show up during enumeration (e.g., in loops).
- configurable: If true, the property can be deleted or changed.
Configuring Attributes:
Object.defineProperty(person, "language", { writable: false, enumerable: false });
Adding Getters and Setters:
Object.defineProperty(person, "fullName", { get: function() { return `${this.firstName} ${this.lastName}`; }});
Listing Properties
- Object.getOwnPropertyNames()
Returns all properties of an object, including non-enumerable ones.
const allProperties = Object.getOwnPropertyNames(person);
2. Object.keys()
Returns all enumerable properties of an object.
const enumerableProperties = Object.keys(person);
Special Use Cases
Getters and Setters in Practice:
Define properties that behave like methods but are accessed as properties.
const obj = { counter: 0 };
Object.defineProperty(obj, "increment", { get: function() { this.counter++; }});Object.defineProperty(obj, "decrement", { get: function() { this.counter--; }});Object.defineProperty(obj, "add", { set: function(value) { this.counter += value; }});Object.defineProperty(obj, "subtract", { set: function(value) { this.counter -= value; }});// Using the propertiesobj.increment;obj.add = 5;obj.subtract = 1;obj.decrement;
Accessing and Modifying Prototype Properties
JavaScript objects inherit properties from their prototype. The Object.getPrototypeOf() method can be used to access the prototype of an object.
Example:
const prototype = Object.getPrototypeOf(person);
Note:
- The delete operator can remove an object’s own properties but not inherited properties.
- Modifying a prototype property affects all objects inheriting from that prototype.
Summary
These methods provide robust tools for defining, modifying, and interacting with object properties in JavaScript. They allow for detailed configuration of object properties, making your JavaScript code more flexible and maintainable. For further details, you can refer to a comprehensive JavaScript object reference guide.