Object Oriented Programming (Inheritance) - PintoGideon/Recursive-React-Tree-Component GitHub Wiki
function userCreator(name,score){
let newUser=Object.create(userFunctionStore);
newUser.name=name;
newUser.score=score;
return newUser
}
userFuctionStore={
sayName:function(){
console.log("I'm"+this.name)
}
increment:function(){
this.score++
}
}
const user1=userCreator('Phil',3)
user1.sayName() //Phil
Now , I want create an object that has all the properties of the user1
plus some added functionality.
function paidUserCreator(paidName,paidScore,accountBalance){
const newPaidUser=userCreator(paidName,paidScore);
Object.setPrototypeOf(newPaidUser,paidUserFunctionStore);
newPaidUser.accountBalance=accountBalance;
return newPaidUser
}
const paidUserFunctionStore={
increaseBalance=function(){
this.accountBalance++
}
Object.setPrototypeOf(paidUserFunctionStore,userFunctionStore)
const paidUser1=paidUserCreator('Alyssa',8,25);
paidUser1.increaseBalance();
paidUser1.sayName();
Subclassing Review
First let's see how call
and apply
works. javaScript functions have an implicit this
parameter which refers to the object to the left of the dot on which the function is being called, unless we override that by calling the function using .call()
and .apply()
which let's us set the this
inside the function.
function userCreator(name,score)
{
this.name=name;
this.score=score;
}
Since we are running a function with the new
keyword, we have to understand that functions can also call properties on it.
useCreator.prototype.increment=function(){
this.score++
}
userCreator.prototype.sayName=function(){
console.log("Hi I am " + this.name);
}
const user1=new userCreator('Phil',10);
user1.sayName();
function paidUserCreator(name,score,accountBalance){
userCreator.call(this,name,score);
this.accountBalance=accountBalance;
}
paidUserCreator.prototype=Object.create(userCreator.prototype)
paidUserCreator.prototype.increaseBalance=function(){
this.accountBalance++
}
const paidUser=new paidUserCreator('Phil',10,9);
paidUser.increaseBalance();
``