Matrym
Matrym

Reputation: 17053

Variable is Undefined

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<script type="text/javascript" src="lb-core.js"></script>
<script type="application/javascript">
var lbp = {
    defaults: {
        color: "blue"
    },
    init: function(config) {
        if(config) {
            for(prop in config){
                setBgcolor.defaults[prop] = config[prop];
            }
        }
        var bod = document.body;
        bod.style.backgroundColor = setBgcolor.defaults.color;
    }
}
window.onload = lbp.init();
</script>
</HEAD>
<body>
<div id="container">test</div>
</body>
</HTML>

Why does bod come back as undefined when the above is called at window.onload?

Upvotes: 0

Views: 1593

Answers (3)

Nick Craver
Nick Craver

Reputation: 630349

Your code needs a few teaks, here's an overall fix:

var lbp = {
    defaults: {
        color: "blue"
    },
    init: function(config) {
        if(config) {
            for(prop in config){
                lbp.defaults[prop] = config[prop];
            }
        }
        var bod = document.body;
        bod.style.backgroundColor = lbp.defaults.color;
    }
}
window.onload = lbp.init;

Previous it was calling init instantly because window.onload = lbp.init() was assigning the result of lbp.init to the onload function, not assigning the actual function, this is fixed above.

Also, not sure where setBgcolor comes from in your code, I believe you meant lbp here, it works in the same code above, give it a test.

Upvotes: 2

SLaks
SLaks

Reputation: 887195

Change it to

window.onload = lbp.init;

When you write window.onload = lbp.init(), you are calling the init function, and assigning whatever it returns to window.onload.
Therefore, the function is being called immediately (before the window is loaded), and you're assigning undefined to window.onload. (Because init doesn't return anything)

You need to assign the init function itself to onload without calling it.

Upvotes: 3

Matt
Matt

Reputation: 44058

Try this:

var bod = document.body;

I don't know why bod comes back as undefined in your code.. it works for me in Chrome. What browser are you running?

Also, are you sure it's bod that's undefined? Not setBgcolor or something else?

EDIT:

Change this line of code:

window.onload = lbp.init();

To this:

window.onload = lbp.init;

You're currently assigning the result of lpd.init() to onload.. you need to just assign the reference.

Upvotes: 1

Related Questions