views:

58

answers:

4

Why doesn't this work? Maybe someone could enlighten me :P

var balloon = function(){

};
balloon.prototype.iHeight = document.getElementById("wrapper").clientHeight;

window.onload = function(){
    var oBalloon = new balloon();
}

Im just trying to understand prototype a little better.

+2  A: 

Your code is probably running before the DOM loads, when there is no wrapper element.

SLaks
A: 

Maybe you want to try:

var balloon = function(){
};
balloon.prototype.iHeight = function(){ return document.getElementById("wrapper").clientHeight; }

Then you can call it later, after the DOM loads.

You need it in a function because otherwise JavaScript will try to calculate the value at definition time.

window.onload = function(){
    var oBalloon = new balloon();
    var height = oBalloon.iHeight(); // iHeight would be undefined if you tried to calculate it earlier
}

You could just scrap the prototype method altogether and set the property in the onload handler:

window.onload = function(){
    var oBalloon = new balloon();
    oBalloon.iHeight = document.getElementById("wrapper").clientHeight;
}

Then, you would only set it once, but also guarantee the DOM will have loaded and the property will be valid by then.

What you had is equivalent to:

var balloon = function(){};
var tmp = document.getElementById("wrapper").clientHeight; // at this point, this is not definted: tmp = undefined
balloon.prototype.iHeight = tmp; // undefined
window.onload = function(){
    var oBalloon = new balloon();
}
palswim
That works but why does it need to be wrapped in a function?
Wieringen
It's because your code is probably running before the DOM is loaded. The code you have works correctly, but you need it to run after the DOM is loaded.
cleek
A: 

The code that you posted works fine. Are you sure you have an element whose id is wrapper?

cleek
A: 

prototypes are only allowed after the object has been initialized so change your code to the following:

Seems after some research I was wrong, what the problem looks like is the fact that your using document.* before the window has loaded, document.* is only available once the <body> has been loaded into the DOM.

so GetElementById() will only work once the actual element your trying to select is inside the dom

var ById = function(i){return document.getElementById(i);}
var balloon = function(){}

window.onload = function(){
    //All elements have loaded now
    var oBalloon = new balloon();
    //The below code should work fine
    balloon.prototype.iHeight = ById("wrapper").clientHeight;
}

From above you can see that document is only being used after the window has loaded

RobertPitt
Not quite correct. `balloon` has been initialized by the function declaration already. `prototype` is fine where he had it.
palswim
yea my mistake was that prototypes can be added to an object regardless of its state but can only be accessed once the object is constructed.
RobertPitt