Object Oriented Programming (The Class Keyword) - PintoGideon/Recursive-React-Tree-Component GitHub Wiki
class UserCreator{
constructor(name,score){
this.name=name;
this.score=score;
}
sayName () {
console.log(`I am ` + this.name);
}
increment(){
this.score++
}
}
const user1= new UserCreator('Phil',4);
user1.sayName();
class paidUserCreator extends userCreator{
constructor(paidName,paidScore,accountBalance){
super(paidName,paidScore);
this.accountBalance=accountBalance;
}
increaseBalance(){
this.accountBalance++
}
}
const paidUser1= new paidUserCreator('Alyssa',8,75);
We call super('Alyysa',8)
. Now previously, the this
keyword was passed by as a reference
to the userCreator
function which performed some side-effects on this.
In this case, here is what's happening behind the super
keyword.
Reflect.construct(userCreator,[Alyssa,8],paidUserCreator)
// This call returns an object which is assigned to `this` in the paidUserCreator.
Conceptually the super
call is similar to calling the userCreator function with a new keyword.
So what are we expecting to happen.
- An implicit object assigned to this.
- Assigning the arguments to the newly created object.
- Setting
__proto__
to userCreator.prototype. - Returning the object.
However, as per the class design, the __proto__
is already set to paidUserCreator.prototype
/
We did it manually before.
super(paidName,score);
The keyword extends
sets the paidUserCreator.prototype's
proto to usercreator.prototype
Advanced concepts
class Person{
constructor(name){
this.name=name;
}
describe(){
return `Person named ${this.name}`
}
}
const jane= new Person("Jane");
const tarzan=new Person("Tarzan");
Class Person has two methods:
- The normal method .describe()
- The special method .constructor() which is called directly after a new instance has been created and initalizes the instance.
Under the hood
The class Person
has the property .prototype
that points to an object that is the prototype of all instances of Person
.
It is interesting to note that both constructs inside class Person (.constructor and describe()) created properties for Person.prototype
, not in Person
.
Also, Person.prototype.constructor
points back to Person
.
const jane= new Person('Jane');
const cheeta= new jane.constructor('Cheeta');
Static properties
class Bar{
static staticMethod(){
return 'staticMethod`;
}
static get staticGetter(){
return 'staticGetter';
}
}
All constructs in the body of the following class declaration create so-called static
properties- properties of Bar
itself.