01 April 23
Frontend developmentin JavaScript?
Yes, you can add getters and setters using the Object.defineProperty()
method in JavaScript. This method allows you to define a property on an object, or modify an existing property, and specify its attributes.
The Object.defineProperty()
method takes three arguments:
The attributes object can contain one or more of the following properties:
value
: The value associated with the property.writable
: A Boolean indicating whether or not the value associated with the property can be changed.enumerable
: A Boolean indicating whether or not the property will be enumerated by a for...in
loop.configurable
: A Boolean indicating whether or not the property can be deleted from the object.get
: A function which will be called when the property is accessed.set
: A function which will be called when the property is set.For example, to create a getter and setter for a property called name
on an object called person
, you could use the following code:
Object.defineProperty(person, 'name', { get: function() { return this._name; }, set: function(value) { this._name = value; } });
Now, when you access the name
property on the person
object, the get
function will be called and when you set the name
property, the set
function will be called.
Frontend development