Let's say I have an Employee
class:
function Employee(name, age, salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
function Manager(name, age, salary, management_school_name) {
...
}
Manager.prototype = new Employee();
Manager.prototype.constructor = Manager;
In the above code, I want to make use of the fact that Employee
encapsulates name
, age
and salary
.
So how should I go about dealing with repeated parameters?
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments