Why can't I set getters and setters in this way inside of the Constructor function?
function zConstructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
set fullname(text) {
const parts = text.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
get fullname() {
return this.firstName + ' ' + this.lastName;
}
}
This getters and setters way works only in classes and Factory functions. What is the reason?
Thanks!
A proper way of doing this is:
function zConstructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
zConstructor.prototype = {
set fullname(text) {
const parts = text.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
},
get fullname() {
return this.firstName + " " + this.lastName;
},
};
Your code does not work because setters and getters are meaningful for Objects only.
You can do it, but a constructor function is just a function, and the syntax of ordinary code blocks does not include the creation of setter and getter functions; there's no way to even make sense of what your code is supposed to mean, as far as the parser is concerned.
What you can do is use Object.defineProperties() to add the properties. Or, probably better, is to create them on the prototype either directly (again, with Object.defineProperties()), or by using a class declaration:
function zConstructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
Object.defineProperties(this, {
fullname: {
set: function(text) {
const parts = text.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
},
get: function() {
return this.firstName + ' ' + this.lastName;
}
}
});
}