+ 2

Can we have getter and setter for Object Constructor in js?

I'm trying this way..but it doesn't seems to work. function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; get this.name = function() { return this.firstName + ' ' + this.lastName; } } Cook = new Person ("Jack","Doe",36,"blue"); Cook.name

21st Mar 2022, 7:37 AM
I Am a Baked Potato
I Am a Baked Potato - avatar
8 Answers
+ 2
I Am a Baked Potato You can do this without a getter then: this.name = function() {....} With a getter maybe define this.name first, "this.name=null", then write your getter Though I believe that's not exactly what you look for. Can you tell me why do you need the getter as an object constructor? hopefully then I can better understand
21st Mar 2022, 8:16 AM
Lior Bakal
Lior Bakal - avatar
+ 1
You need to name the get. Use "get fullName(){....}" instead of "get this.name = ...." See full example here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
21st Mar 2022, 8:03 AM
Lior Bakal
Lior Bakal - avatar
+ 1
lior bakalo Thank uh but I'm asking for Object 'Constructor.
21st Mar 2022, 8:07 AM
I Am a Baked Potato
I Am a Baked Potato - avatar
0
I'm actually practicing js Object and it's Constructor. (with getter and setter) We know that if have to define simple Object literal, we can do it directly like this const person = { firstName: "John", lastName: "Doe", language: "", set lang(lang) { this.language = lang; } }; and also can easily have getter and setter. But what if we have to make bunch of same kind of objects with different Object values? In Object constructor I'm able to have a simple method but not getter and setter like Object literal. So how to do this?
21st Mar 2022, 8:33 AM
I Am a Baked Potato
I Am a Baked Potato - avatar
0
function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; this.name = function() { //debug return this.firstName + ' ' + this.lastName; } } Cook = new Person ("Jack","Doe",36,"blue"); console.log(Cook.name()); const person = { firstName: "John", lastName: "Doe", language: "En", lang(lang){ this.language = lang; } }; const p1 = person; p1.lang("Ru"); console.log(p1.language); p1. language = "Uk"; console.log(p1.language); I hope this helps you understand constructors: https://code.sololearn.com/W1O58CP71vml/?ref=app
21st Mar 2022, 9:03 AM
Solo
Solo - avatar
0
Figured it out :) Object.defineProperty(Person.prototype, 'name', {get: function() { return this.firstName +' '+ this.lastName }});
21st Mar 2022, 10:34 AM
I Am a Baked Potato
I Am a Baked Potato - avatar