wong2
wong2

Reputation: 35720

Why can't I use 'this' when creating this javascript object literal?

The html:

<div id="slide">
    <div>This is one</div>
    <div>This is two</div>
    <div>This is three</div>
</div>

JavaScript:

var slider = {
    div: document.getElementById("slide"),
    divs: this.div.getElementsByTagName("div")
};

alert(slider.divs.length);

jsfiddle: http://jsfiddle.net/CAzN8/

When I run this, Chrome said this.div is undefined. What's wrong here?

[UPDATE] I found that if I change the code to:

var tmp = document.getElementById("slide");
var slider = {
    div: tmp,
    divs: tmp.getElementsByTagName("div")
};

It works. But why can't the first case work?

Upvotes: 1

Views: 184

Answers (4)

Mike Neumegen
Mike Neumegen

Reputation: 2486

The reason you can't use this is because the JSON object hasn't actually been initialized yet. This is how I would do what you're trying to do:

var slider = {
    my_div: document.getElementById("slide");
};

slider.my_divs = slider.my_div.getElementsByTagName("div");
alert(slider.my_divs.length);

or

var my_div = document.getElementById("slide");

var slider = {
    my_div: my_div,
    my_divs: my_div.getElementsByTagName("div")
};

alert(slider.my_divs.length);

Upvotes: 1

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

Your code doesn't work cause, when creating the object literal (what's inside brackets), the object doesn't exist yet, so this is undefined.

It's like thinking you could be your own father, you don't exist the moment of your creation.

Upvotes: 0

Corey Sunwold
Corey Sunwold

Reputation: 10254

Because the object hasn't actually been instantiated yet. This will work though:

var slider = {
    div: document.getElementById("slide"),
    divs: document.getElementById("slide").getElementsByTagName("div")
};

or

var slider = {};
slider.div = document.getElementById("slide");
slider.divs = slider.div.getElementsByTagName("div");

Upvotes: 0

tobyodavies
tobyodavies

Reputation: 28099

what this is , is dynamically determined by the method being called, not the lexical block the code resides in.

Simply using this inside the body of a JSON object does not mean it refers to the object being constructed. It almost certainly refers instead to the global window object.

If you want to be able to use this you'd want a constructor:

function Slider(id,tagName){
    this.div  = document.getElementById(id);
    this.divs = this.div.getElementsByTagName(tagName);
}

s = new Slider('slide','div')

Upvotes: 3

Related Questions