I’m following along the tutorial from Traversy Media on JS. During this video he created a:
- Person constructor with
firstName
andlastName
andprototype.greeting
function. - Customer constructor that inherits the parameters of Person (
firstName
andlastName
) and adds new parameters (phone
andmembership
) - Customer inherits prototypes of Person
- Changes
Customer.prototype.constructor
toCustomer
This is the part that I don’t understand. Is this just a good practice just to keep things organised or it has some other purpose?
// Inherit prototypes
Customer.prototype = Object.create(Person.prototype);
// Use Customer Constructor
Customer.prototype.constructor = Customer;
// Making separate greeting method for Customer
Customer.prototype.greeting = function() {
return `Hello to our company ${this.firstName} ${this.lastName}!`;
}
I have commented out Customer.prototype.constructor = Customer
to see if this changes the output or produces some error, but when I call greeting function on Customer1 it still executes without any error.
So, what’s the point of changing the name of the inherited prototype constructor?
Below is whole code if you want to reproduce it for yourself:
// Person constructor
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.greeting = function() {
return `Hello ${this.firstName} ${this.lastName}!`;
}
const Person1 = new Person('Jan', 'Kowalski');
console.log(Person1.greeting());
// Customer constructor
function Customer(firstName, lastName, phone, membership) {
// firstName and lastName are concurrent by coincident
Person.call(this, firstName, lastName);
this.phone = phone;
this.membership = membership;
}
// Inherit prototypes
Customer.prototype = Object.create(Person.prototype);
// Use Customer Constructor
Customer.prototype.constructor = Customer;
// Making separate greeting method for Customer
Customer.prototype.greeting = function() {
return `Hello to our company ${this.firstName} ${this.lastName}!`;
}
// Create Customer
const Customer1 = new Customer("Alfred", "Michigan", "874255355", "premium");
console.log(Customer1);
console.log(Customer1.greeting());