+ 1
I know how to set and get in literal and construct objects but i don't know where are they functioning
6 Réponses
+ 6
yaqub abdulmalik I'm not sure I understand what you mean by "where they are functioning."
It might help if you ask your question with some code we can reference.
Take a look at this code sample I created and let us know which part you are unclear about.
https://code.sololearn.com/WuswYAzn9MWs/?ref=app
+ 6
Sir David Carroll has already well explained with ES6 syntax. Nonetheless, since you made mention of constructor function in your post, I guess you might be more familiar with ES5 syntax?. Let's see..
// constructor
function Author(name, book, year) {
this.name = name;
this.book = book;
this.year = year;
}
the constructor above can be used to create different authors, by invoking with "new" keyword. E.g
var benCarson = new Author("Ben Carson", "Think Big", 2005 );
To create accessor properties (getter / setter) to get details of each author, we can use "Object.defineProperty".
Object.defineProperty(Author.prototype, "details", {
get: function() {
return {
name: this.name,
book: this.book,
year: this.year
}
}
})
The "details" property is defined on the constructor's prototype so it can be accessed by all objects created with the constructor.
NB: "enumerable" and "configurable" of the property can also be set.
+ 3
what was the question again?🤨
+ 3
if for example, you want to make a list of authors, then youd use the constructor to set the name, book title and the year it was written. when you want to retrieve the details about these authors or a particular author, youd use the getter. so youd probably store each author in an array so that you can access them by some criteria such as index number or by using something like the inbuilt filter function.
+ 1
I mean what can we make with setter and getter?
+ 1
thanks you all for your suggestion