Reputation: 12132
Why is it that just by using call
you're adding properties to the Employee
instance named jc
?
I'm wondering why jc.hasOwnProperty('firstName');
results to true
.
I didn't even do prototype
inheritance yet. This is all the code, no more no less:
I understand that call
just changes the this
while passing in arguments, but to add properties? I don't know what's going on...
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
function Employee(firstName, lastName, position){
Person.call(this,firstName,lastName);
this.position = position;
}
var jc = new Employee('JC','Viray','Developer');
jc.hasOwnProperty('firstName'); //true
UPDATE
I get it now.. the solution to my problem is:
stop thinking in C#/Java mentality.. I lost track that Person
is still a FUNCTION
despite it being a "constructor type function"... -_- once a function, still a function..
Upvotes: 1
Views: 65
Reputation: 83366
I'm wondering why jc.hasOwnProperty('firstName'); results to true.
Because of this line in the Person
function:
this.firstName = firstName;
When you say
Person.call(this, firstName, lastName);
You're actually calling the Person
function, and telling Person
to set its this
value to what's provided in the first argument—in your case, the Employee object you're in the process of building. The subsequent arguments to call
then get passed along as regular parameters.
As a result, Person
gets called with this
set to be your current Employee
object, and picks up a firstName
and lastName
property.
Or consider an alternate example.
var obj = { };
Person.call(obj, "Adam", "Rackis");
obj.hasOwnProperty('firstName'); //still true
Upvotes: 4
Reputation: 816770
You are calling
Person.call(this,firstName,lastName);
which means that the function Person
, this
refers to whatever this
refers to in Employee
(a new object). Inside Person
, you are assigning values to this.firstName
and this.lastName
.
You could have written the same as:
function Employee(firstName, lastName, position){
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
}
I understand that call just changes the this while passing in arguments, but to add properties?
call
does not add properties to the object, but your function does. And that's exactly why it is used in this case. You want to apply everything inside Person
to the new object as if you had called new Person(a, b)
.
Upvotes: 4