Link to home
Start Free TrialLog in
Avatar of stdev07
stdev07

asked on

Javascript OOP encapsulation trouble

Hi,

I am trying to prove some concepts in OO javascript, with the help of the following code;

[code]

function catClass(){
    this.sound = "miau";
    this.makeSound = function(){
        alert(this.sound);
    }
}

var cat = new catClass();

[/code]

This code is held inside the <head> part of the HTML document.

If I call the function cat.makeSound(); then the correct alert will show ("miau").

But if I use this command:

window.onload = cat.makeSound;

Then it shows [undefined] as alert message! That means it loses its reference, I know, and I would like to know how to prevent that.

Thanks in advance!
Avatar of basicinstinct
basicinstinct
Flag of Australia image

it works if you do this:

<body onload="cat.makeSound();">
or this:

window.onload = function(){cat.makeSound();};
even (oddly) this:

window.onload = cat.makeSound();

??
oh no, i was getting confused, it just got called at that point, sorry...
THis definitely works:

window.onload = new Function("cat.makeSound();");
so in summary, these definitely work:

window.onload = new Function("cat.makeSound();");

OR

<body onload="cat.makeSound();">
ASKER CERTIFIED SOLUTION
Avatar of KhoiNqq
KhoiNqq

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of KhoiNqq
KhoiNqq

Put in the onload attribute will works also:
 <BODY onload="cat.makeSound.apply(cat);">