I have this simple Javascript code to write some modules, but I don't know why I get undefined results even when I'm calling the function from inside:
window.onload = function () {
function testFunction() {
this.hours = null;
function getHours() {
return this.hours;
}
alert(getHours());
return {
getHours: function () {
return getHours();
}
}
}
var test = new testFunction();
alert(test.getHours());
}
I think I've problem in understanding THIS keyword in javascript and using it inside javascript constructors.
Thank you.
thisinside yourgetHoursfunction is not the samethisoutside of it.obj.myFunc()thenthis === obj. But if you just callmyFunc()thenthis === window(ornullin ES5 strict mode!)hourproperty! That could have been added to the returned object too, but then it wouldn't have been private.