I referred this question/answer to understand prototypical inheritance.
I got to know to extend a method , we need to define Person.prototype.getName
in base class. So that in child class it can be called as myCustomer.sayMyName();
Code in the answer can be summarized as follows :
function Customer(name) {
this.firstName = name;
};
function User() {
}
Customer.prototype.hi = function() {
console.log('Test method of parent');
}
User.prototype = new Customer('shaadi');
var myUser = new User();
myUser.hi();
But the question is if I can call the same with following syntax, why should I use prototype?
My code:
function Customer(name) {
this.firstName = name;
this.hi= function() {
console.log('Test method of parent');
}
};
function User() {
}
User.prototype = new Customer('shaadi');
var myUser = new User();
myUser.hi();
I could use the method of parent without defining Customer.prototype.hi
, then why/when should Customer.prototype.hi
be used?
If both solutions give me access to parent's method, why should I choose former?