I have a function in javascript.
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.name = function() {return this.firstName + " " + this.lastName;};
}
Why we can't add a property to the constructor in javascript like this?
Person.hairColor = "black";
We can add a property to object easily like this.
myPerson = new Person("firstName","lastName",23,"brown");
myPerson.hairColor = "black";
Why the first one is not possible, why javascript restricts to add a property to constructor?
If you assign a property to Person.hairColor
, that can only be accessed via Person.hairColor
, and it won't be inherited to instances, as instances inherit from Person.prototype
. So if you add a property to that, e.g. Person.prototype.hairColor
, then that will be inherited and can be accessed via the instances (myPerson.hairColor
).
Note that setting myPerson.hairColor
won't change the value in the prototype, but will create a new property on the instance, e.g.:
myPerson.hairColor += " and brown";
console.log(
Person.prototype.hairColor, // "black"
myPerson.hairColor, // "black and brown"
);