2 Questions:
ADDITION after reading answer of @Box9: What about Code A vs. Code C?
function employee(name,jobtitle,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
}
employee.prototype.salary=null;
function employee(name,jobtitle,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
employee.salary=null;
}
function employee(){}
employee.prototype.name=null;
employee.prototype.jobtitle=null;
employee.prototype.born=null;
employee.prototype.salary=null;
Apologies ahead of time, I realize there have been other SO questions on .prototype and many web tutorials, however those explanations seem to be either overly simplistic or just technically over my head.
In your example, Code A is correct, while Code B is not.
To explain, we can think about employee from three different aspects:
prototype.this within the employee() function.employee.Now relating back to your two code examples,
employee.prototype.salary = null in Code A is correct because it is setting the starting salary for the "standard" employee.
employee.salary = null in Code B is incorrect because it is setting the salary for all employees as a group - i.e. it's not just a default value, but a single, blanket value for all employees. It doesn't matter that this code is inside the employee() function - the only difference the function makes is that it allows you to use the this keyword to refer to the "particular" employee that is currently being constructed as a result of calling new employee().
Firstly, Code A and B will have different results. Code A has a constructor for an object and adds a property to its prototype. This means all instances of employee will have a field called salary, which is null. As is the normal behaviour for prototype properties, if any of those instances write to the property, it will create a local copy for the object.
So, using Code A:
var e = new employee('Bob', 'janitor', 1978);
alert(e.salary); // null
var f = new employee('Alice', 'teacher', 1976);
f.salary = 20000;
alert(f.salary); // 20000
alert(e.salary); // null
In the case of Code B, none of the instances of employee will have salary as a property, but the constructor will, e.g. employee.salary will exist, and be more like a static class variable in classical inheritance. You might do that if you wanted to have a value available for all instances, e.g. employee.RETIREMENT_AGE = 65, but you would usually do that after the constructor, not in it (you're assigning the same thing repeatedly).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With