I’m trying to get a better understanding of OOP in Javascript. Can someone please explain how the create method is being used in the example below and an alternative? I’ve looked it up on the web and reviewed several posts on SO and still don’t have a solid grasp of what’s happening in the code below. I’ve provided comments to illustrate my understanding. Please correct me where I’m wrong.
This example is used to override a method from a base class:
// Defines an Employee Class
function Employee() {}
// Adds a PayEmployee method to Employee
Employee.prototype.PayEmployee = function() {
alert('Hi there!');
}
// Defines a Consultant Class and
// Invokes the Employee Class and assigns Consultant to 'this' -- not sure and not sure why
// I believe this is a way to inherit from Employee?
function Consultant() {
Employee.call(this);
}
// Assigns the Consultant Class its own Constructor for future use -- not sure
Consultant.prototype.constructor = Consultant.create;
// Overrides the PayEmployee method for future use of Consultant Class
Consultant.prototype.PayEmployee = function() {
alert('Pay Consultant');
}
This code:
Is invoking the Employee constructor when the Consultant constructor is invoked (i.e., when an instance of Consultant is created). If the Employee constructor were doing any sort of initialization, then it would be important that it be called when the Consultant “subtype” was created.
This code:
is a bit of mystery. It implies that there is a function named create which is a property of the Consultant function object. However, in the code sample you posted, there is no such property. In effect, this line is assigning
undefinedto the Consultant constructor.Your question doesn’t ask, but just FYI, I think what you probably want instead of that line with the create function, is this:
That’s the prototypal inheritance pattern. It is certainly not the only or necessarily best approach, but I like it.
Update
If Employee takes an argument, you can handle that like so: