Reputation: 1849
Good Morning in my timezone.
I am learning JavaScript inheritance and i start reading the MDN pages. I understand that we have to use the prototype property from the constructor to build a inheritance chain, for example :
function Employee(){
this.name = "Dave";
this.dept = "";
}
function Manager(){
this.projects = [];
}
Manager.prototype = new Employee;
If we do this :
var jane = new Manager();
jane.name -> It will retrive "Dave" because it will find on the Employee object.
What i can not understand is if you do this way:
function Employee(name,dept){
this.name = name || "Dave";
this.dept = dept || "General";
}
function Manager(){
this.base = Employee;
this.base("Jack","CustpmDept");
this.projects = [];
}
Now if i do the same :
var jane = new Manager();
jane.name -> It will retrive "Jack" because it will find on the Employee object.
In this last example i did not use the line Manager.prototype = new Employee; And it stil works , the Manager object have as their prototype object the Employee object. How is this possible ? Can you clarify me
Thanks in advance
Best regards
Upvotes: 2
Views: 2165
Reputation: 13549
Check out the following code:
function Employee(name,dept){
this.name = name || "Dave";
this.dept = dept || "General";
console.log(this instanceof Manager);
}
function Manager(){
this.base = Employee;
this.base("Jack","CustpmDept");
this.projects = [];
}
var jane = new Manager();
console.log(jane.name);
In the example
console.log(this instanceof Manager);
returns true because when you call
this.base = Employee;
you are basically sending Manager's this to the Employee. this.name and this.dept are actually attached to the Manager.
Upvotes: 3
Reputation: 7575
OK so js is fun with how it handles context.
When you call this.base()
in the Managers 'constructor' you are calling the function base
from the context of that manager. So by the time we get to the this.name =
bit, the keyword this
refers back to that manager, not the function that line was written in.
Upvotes: 0
Reputation: 1848
In the latter, new Manager()
returns 'Jack' because you call this.Employee('Jack', 'CustpmDept')
which sets jane.name
to 'Jack', because 'this' is 'Manager', or in this case, 'jane'.
It's a bit confusing.
Upvotes: 0
Reputation: 388436
function Manager(){
this.base = Employee;
this.base("Jack","CustpmDept");
this.projects = [];
}
when you used the this.base("Jack","CustpmDept")
, in invokes the Employee
with this
inside the Employee
pointing to the new manager instance
Upvotes: 2
Reputation: 1153
The second way is like constructor stealing. this.base("Jack","CustpmDept");
will call the Employee
constructor, since this
key word will point to the object to be creates when we new the instance, so jane can get these properties.
Upvotes: 1