简体   繁体   中英

prototype and document.getElementById()

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.

在没有wrapper元素的情况下,您的代码可能在DOM加载之前运行。

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM