actually, it’s not strictly an OOP question… prob is var inside fn inside nested fn returns ‘undefined’…
function Employee() {
this.manager = "Ravi Gupta";
this.dept = "sales";
this.city = "San Francisco";
this.setVacationDays = function(years) {
vacationDays = years * 5;
[B]console.log(vacationDays); // ***** prints 'undefined'[/B]
console.log('years: ' + years); // prints '4' (i.e., this var is fine)
};
}
var Jon = new Employee();
var JonVacationDays = Jon.setVacationDays(4);
[B]console.log(JonVacationDays); // ***** prints 'undefined'[/B]
The reason JonVacationDays returns “undefined” is because you aren’t returning any value in the “setVacationDays” function.
this.setVacationDays = function(years) {
var vacationDays = years * 5;
console.log(vacationDays); // ***** prints 'undefined'
console.log('years: ' + years); // prints '4' (i.e., this var is fine)
return vacationDays;
};
If the only action done in “setVacationDays” is multiplying by 5, then you can just return that (“return years * 5;”)
Edit: if I print “console.log(vacationDays)” it does return 20.
You need to add a return-statement to a function if you want the function to return a value. If you just want to execute a function, you don’t need to write a return-statement.
Eventough my “solution” works, it’s not a decent way of writing. I’ll try to clarify.
We’re writing a class “Employee”, so we should follow the OOP “standards”
We’ve created a setVacationdays-function, but we’re returning a value. Basically, when writing a “setter”-function, you never return a value. You either write a getter-function or just call upon the variable.
We haven’t declared the vacationDays-variable
So, lets rewrite it:
function Employee() {
this.manager = "Ravi Gupta";
this.dept = "sales";
this.city = "San Francisco";
this.vacationDays = 5;
this.setVacationDays = function(years) {
this.vacationDays = years * 5;
};
this.getVacationDays = function(years) {
return this.vacationDays;
};
}
var Jon = new Employee();
Jon.setVacationDays(4);
console.log(Jon.vacationDays);
console.log(Jon.getVacationDays());
So the code was slightly altered. In the first console.log, I call upon the variable using the new Employee, Jon, which was created earlier. In the second console.log, I call upon the getter-function. The only job the getter-function has is to return this.vacationDays.
I hope it’s a bit more clear now, it’s not easy explaining it in English