I am learning how to implement OOP in JavaScript using constructor functions, and I am facing some confusion regarding how sub types are created.
My current understanding is, the new keyword is what works behind the scenes to do the following:
- create an empty
thisobject - set the
__proto__property of thethisobject to point to the prototype property on the constructor function - return the
thisobject
That is why we do not have to explicitly return an object from our constructor function, the new keyword does it for us.
In the example below I am creating a PaidUser sub type of the User type:
function User(name) {
this.name = name;
}
function PaidUser(name, balance) {
User.call(this, name);
this.balance = balance;
}
Following examples I have seen, I am extending from the User types properties in the PaidUser type and setting the context of this in the User constructor to point to the lexical this with User.call(this,...)
My confusion is regarding how does User.call() affect what is implicitly returned by the new keyword from the PaidUser constructor?
For example in the PaidUser constructor i define the this.balance property to the this object, now it is my understanding it is the this object which will be returned from the PaidUser constructor, when called with the new keyword. How does User.call(this, name) ever get returned or effect the object returned from the PaidUser constructor.
Currently according to my understanding, this is what imagine is sort of happening behind the scenes:
function PaidUser(name, balance) {
this = {
__proto__:PaidUser.prototype
};
this.balance = balance;
User.call(this, name); // {this.name:name}; //lexical this
// why is the object returned from User.call() just floating around
// neither assigned to a variable or returned ?
return this; // how does this.name ever become part of the returned object?
}
I would really appreciate any help and explanation regarding the steps taken by the new keyword when when the PaidUser constructor function is called.
With much thanks and appreciation.
User.call(this, name)explicitly makesthisin theUser()function be the samethisthat thenewcall toPaidUsercreated.User.call(this,name)it calls the User function and sets the name property on the PaidUserthisobject? I guess i got lost in all the constructor creation specifics and forgot to remember we are infact calling a function with User.call() Thankyou very much!newkeyword basically does this:function customNew(Constructor, ...args) { const obj = Object.create(Constructor.prototype); const result = Constructor.apply(obj, args); return result && typeof result === 'object' ? result : obj;)