Prototype and document.getElementById ()

Why is this not working? Maybe someone can enlighten me: P

var balloon = function(){

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

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

I'm just trying to understand the prototype a little better.

+3
source share
4 answers
Prototypes

allowed only after the initialization of the object, so change the code to the following:

It seems that after some research I was mistaken, the problem is that when used document.*before loading the window document.*is only available after it has <body>been loaded into the DOM.

therefore, it GetElementById()will only work after the actual item you are 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;
}

, ,

+1

, , DOM, wrapper.

+2

, :

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

, DOM.

, JavaScript .

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

onload:

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

, , DOM , .

, , :

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

, , . , , ?

0

Source: https://habr.com/ru/post/1764581/


All Articles