有人可以解釋爲什麼我會在下列每種情況下得到結果嗎?我希望理解爲什麼結果是關於JavaScript如何在範圍內工作的結果,如果這是問題所在。在第一個例子中,我的代碼正常工作。解釋這個未捕獲的類型錯誤:對象[對象對象]的屬性'x'不是函數
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
我得到的遺漏的類型錯誤。
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
如果工作正常試。儘管我的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());
[很好的解釋](http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/) – RobH
爲徹底性。 – rGil
@chris_s:不客氣。最終,最乾淨的解決方案是使用*** rGil ***發佈的內容。但是,IMO更好的是通過將所有方法放在'Employees.prototype'上來使用原型繼承。然後它們在所有Employee對象之間共享,而不是爲每個對象重新創建。 – 2013-05-17 13:33:58