Q1) How is this possible?!
function employer(name) { this.name = name;};
var fred = new employer('Fred');
Isn’t employer a function rather than a class?
Q2) What does
employer.prototype
signify?
and finally
Q3) How does this work?
employer.prototype.salary = null;
fred.salary = 2000;
Can someone please give simple explanation? Please 🙂
As you asked for a simple explanation, here we go:
Q1) This is possible because JavaScript functions are first-class (i.e. they are objects, and you can create
newobjects).Q2) A
prototypeis an object from which other objects inherit properties. Properties of an objects prototype will be available to all instances of that object.Q3) This means that all instances of
employerwill have a propertysalarywith the valuenull. The instance ofemployercalledfredsimply overrides that initialnullvalue with2000. It’s the samesalaryproperty though (when you use a property, the scope chain is searched until a match is found. In this case, a match is found on the object prototype).Quick example: