- Not with dot-separated property notation
- Adding peroperty or method to constructor is not as simple as to the indivial objects.
- The property dot-separated notation is for individual object, not for the object type.
-
father.location = "Bali"; // works
Person.location = "Bali"; // doesn't work
Person.location
will give the value as the comment just like father.location
as if it works, but if you check the constructor function amd individual objects, you'll see it doesn't get added anywhere.
- A new property needs to be added directly to the constructor function
- Existing Person constructor
-
function Person(first, last, year) {
this.firstName = first;
this.lastName = last;
this.birth = year;
};
- Created objects
-
const father = new Person("John", "Doe", 1950);
const mother = new Person("Sally", "Mae", 1955);
- Add new property with default value to the constructor
-
function Person(first, last, year) {
this.firstName = first;
this.lastName = last;
this.birth = year;
this.location = "Bali";
};
- Let's create object using the constructor again
-
const sister = new Person("Puff", "Tail", 1985);
const brother = new Person("Dodo", "Bird", 1980);
- Results
-
father;
mother;
sister;
brother;
- Note that the new property only added to newly created objects after the addition, doesn't affect the previously made objects.
- Similarly, a new method needs to be added directly to the constructor function
- Existing Person constructor
-
function Person(first, last, year) {
this.firstName = first;
this.lastName = last;
this.birth = year;
};
- Created objects
-
const father = new Person("John", "Doe", 1950);
- Adding a function to the constructor
-
function Person(first, last, year) {
this.firstName = first;
this.lastName = last;
this.birth = year;
this.changeName = function (name) {
this.lastName = name;
};
};
- It takes effect only to objects created after the constructor update.
- Results
-
father;
father.changeName("Smith");
father;
const mother = new Person("Sally", "Mae", 1955);
mother;
mother.changeName("Doe")
mother;