有人可以解释为什么我在以下每种情况下都会得到我的结果吗?如果这是问题所在,我想了解为什么结果是关于 JavaScript 如何与范围一起工作的结果。在第一个示例中,我的代码运行正常。
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());
如果我将 移动addSalaryFunction
到Employees
函数中,并且在下面this.addSalary
我得到未捕获的 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());
但是如果我移动addSalaryFunction
上面的this.addSalary
if 再次正常工作。尽管我的 IDE 告诉我我的局部变量addSalaryFunction
是多余的。
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());