Mohammad Mohammad - 4 months ago 9
Javascript Question

Why this javascript class returns undefined

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.

Answer

Your (initial) problem is here:

return {
    getHours: function () {
        return getHours();
    }
}

By making a "naked" call to getHours() inside this function you're losing any this context that you had.

Instead, do this:

return {
    getHours: getHours
}

i.e. return an object that contains a reference to the desired function. When you call test.getHours() it'll then correctly pass test as this to getHours.

The other issue is that because you're using return to expose a set of functions, that returned object becomes the newly constructed this and it no longer refers to the this that you added hours to!

This is an unfortunate mishmash of two (or maybe more) JS OOP techniques and they're conflicting with each other.