This is completely fine, you are inheriting the properties of the Person
through the call to the parent constructor Person.call(this, ...)
and you are passing the this
of the Employee
instance to the Person
constructor function.
When you invoke call
and pass the this
context of the Employee
instance, it will actually use the this
of the Employee
to do these assignment operations:
this.firstname = firstname;
this.lastname = lastname;
this.gender = gender;
this.name = function(){
return this.firstname +" "+this.lastname;
}
Here this
refers to the new Employee
instance. Since the above assignment makes these properties appear on the new Employee
instance as own properties the hasOwnProperty
returns true
when you use any of these properties with the hasOwnProperty
method.
This is the correct way to do inheritance for data properties in JavaScript. In case of methods we should put them in the prototype
.
This is because the data properties should not be shared between the different instances of the Employee
but the methods can, as they imply behaviour which can be common.
If you do not put the methods in the prototype
and put them as own properties, it would become an overhead as the same logic would be present but the method would be a different instance for every instance of your constructor.
To complete your example, the hasOwnProperty
is returning false
for the name
method as it is on the prototype
, while other data properties will return true
:
var Person = function(firstname, lastname, gender) {
this.firstname = firstname;
this.lastname = lastname;
this.gender = gender;
}
Person.prototype.name = function() {
return this.firstname + " " + this.lastname;
}
var Employee = function(firstName, lastName, gender, title) {
Person.call(this, firstName, lastName, gender);
this.title = title;
};
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
var e = new Employee('Abc', 'efg', 'Tree', 'CEO');
//Prints true
console.log(e.hasOwnProperty('firstname'));
//Prints false
console.log(e.hasOwnProperty('name'));
The Function.prototype.call
basically uses the supplied this
context, it has nothing to do with inheritance in general. Basically you are re-using the Person
constructor function logic and populating the data property values of the Employee
instance when you do this.