Getting and Setting Property Descriptors in JavaScript (Part 3)
In the previous post, I talked about the meaning of various property attributes. Now let's see how we can define properties with desired attributes.
The Object.defineProperty
and Object.defineProperties
functions are somehow the opposites of Object.getOwnPropertydescriptor
and Object.getOwnPropertydescriptors
functions in that the outputs of the latter functions can be used as the input to the former functions.
In the following code snippet, the syntax of Object.defineProperty
is illustrated:
let ali = {};
Object.defineProperty(ali, "age", {
value: 19,
writable: true,
enumerable: true,
configurable: true,
});
Object.defineProperty(ali, "name", {
get: function () {
if (typeof this._name === "undefined") {
this._name = "Ali";
}
return this._name;
},
set: function (name) {
this._name = name;
},
enumerable: true,
configurable: true,
});
Or, you can define all properties at once using Object.defineProperties
, like this:
let ali = {};
Object.defineProperties(ali, {
age: {
value: 19,
writable: true,
enumerable: true,
configurable: true,
},
name: {
get: function () {
if (typeof this._name === "undefined") {
this._name = "Ali";
}
return this._name;
},
set: function (name) {
this._name = name;
},
enumerable: true,
configurable: true
},
});
Interesting. I would like to see this with ES6 syntax as well.
Great job. Learning new things.
In your post I think everyone will benefit.More like this post.
i liked this post... thanks for sharing
This is very useful and convenient way to define properties.
Can i resteem sir, now?
You got a 15.04% upvote from @upme requested by: @ghasemkiani.
Send at least 1 SBD to @upme with a post link in the memo field to receive upvote next round.
To support our activity, please vote for my master @suggeelson, as a STEEM Witness
Can i reasteam you
What's up Steemians ?? If you post a new post , comment @originalworks or !originalworks to receive a 1.5% upvote by n bot if your content is original .
Keep Calm And Steem On :)
Please Follow , Resteem , Upvote or Comment - @jacoknoetze
The @OriginalWorks bot has determined this post by @ghasemkiani to be original material and upvoted(1.5%) it!
To call @OriginalWorks, simply reply to any post with @originalworks or !originalworks in your message!