开发者

prototype and document.getElementById()

开发者 https://www.devze.com 2023-01-15 19:47 出处:网络
Why doesn\'t this work? Maybe someone could enlighten me :P var balloon = function(){ }; balloon.prototype.iHeight = document.getElementById(\"wrapper\").clientHeight;

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 try开发者_开发知识库ing to understand prototype a little better.


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


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


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


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消