+ 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
6 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
+ 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
+ 1
lior bakalo Thank uh but I'm asking for Object 'Constructor.
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?
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
0
Figured it out :)
Object.defineProperty(Person.prototype, 'name', {get: function() { return this.firstName +' '+ this.lastName }});