简体   繁体   中英

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?

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')

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

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");

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.

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