Could someone please clarify why the outcomes differ in each scenario described below? I am trying to grasp the way JavaScript interacts with scope, assuming that is the root of the issue. In the initial example, my code behaves as expected.
var Employees = function(name, salary) {
this.name = name;
this.salary = salary;
this.addSalary = addSalaryFunction;
this.getSalary = function() {
return this.salary;
};
};
var addSalaryFunction = function(addition) {
this.salary = this.salary + addition;
};
var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());
If I relocate the addSalaryFunction
inside the Employees
function and position it beneath this.addSalary
, I encounter an Uncaught TypeError.
var Employees = function(name, salary) {
this.name = name;
this.salary = salary;
this.addSalary = addSalaryFunction;
this.getSalary = function() {
return this.salary;
};
var addSalaryFunction = function(addition) {
this.salary = this.salary + addition;
};
};
var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());
However, if I move the addSalaryFunction
above this.addSalary
, the code functions correctly again. My IDE indicates that the local variable addSalaryFunction
seems redundant.
var Employees = function(name, salary) {
this.name = name;
this.salary = salary;
var addSalaryFunction = function(addition) {
this.salary = this.salary + addition;
};
this.addSalary = addSalaryFunction;
this.getSalary = function() {
return this.salary;
};
};
var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());