function Employee(name, age, salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
function Manager(name, age, salary, management_school_name) {
Employee.call(this,name,age,salary); //Call base constructor function
...
}
Manager.prototype = new Employee(); //Create prototype chain
Manager.prototype.constructor = Manager;
Another way to create prototype chain is using Object.create
.
Manager.prototype = Object.create(Employee.prototype); //Create prototype chain
This is how Object.create is implemented internally:
function create(proto) {
function F() {};
F.prototype = proto ;
return new F();
}
So when should we use Object.create
and new Employee()
to create prototype chain?
Object.create
does not have any construction logic to create an object while we could have construction logic inside Employee
, like this.default = "default"
. In this case, using new Employee()
is not much different from Object.create
. But if we need to avoid construction logic completely, we could use Object.create