I'm trying to create a read only property on a constructor function with Javascript. I've remixed the syntax I've found on MDN but this doesn't work:
function Person(data) {
var self = this;
self.firstName = data.firstName || "John";
self.lastName = data.lastName || "Doe";
get fullName() { return self.firstName + " " + self.lastName; }
}
var mike = new Person({ firstName: "Mike", lastName: "Michaelson" });
document.write(mike.fullName);
This will throw an exception:
Uncaught SyntaxError: Unexpected identifier
I've tried other options, including:
{ get fullName() { return self.firstName + " " + self.lastName; } }
And:
get this.fullName() { return self.firstName + " " + self.lastName; }
And:
get self.fullName() { return self.firstName + " " + self.lastName; }
But none of those options work.
This one does work:
function Person(data) {
var self = this;
self.firstName = data.firstName || "John";
self.lastName = data.lastName || "Doe";
Object.defineProperty(self, "fullName", { get: function () { return self.firstName + " " + self.lastName; } });
}
var mike = new Person({ firstName: "Mike", lastName: "Michaelson" });
document.write(mike.fullName);
But obviously this way with defineProperty feels clunky.
What is the correct syntax for defining get-only properties inside constructor functions?
prototype(object.prototype = { get x(){ return this._x; }}- but you can only do this once when declaring the full prototype) or usedefineProperty. If you are making a read-only property, you should actually usedefinePropertyto make it non-writeable. These are the only valid syntactical ways to do this.fullName? If so, please re-read my answer, as I've updated it to accommodate for such a case.Personfunction is / can be no longer used as a constructor function as it breaks inheritance. - Guess I'm just spoiled with C#'s property syntax...