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!
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!
or this:
window.onload = function(){cat.makeSound() ;};
window.onload = function(){cat.makeSound()
even (oddly) this:
window.onload = cat.makeSound();
??
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(); ");
window.onload = new Function("cat.makeSound();
so in summary, these definitely work:
window.onload = new Function("cat.makeSound(); ");
OR
<body onload="cat.makeSound();">
window.onload = new Function("cat.makeSound();
OR
<body onload="cat.makeSound();">
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Put in the onload attribute will works also:
<BODY onload="cat.makeSound.appl y(cat);">
<BODY onload="cat.makeSound.appl
<body onload="cat.makeSound();">