简体   繁体   中英

Need help understanding why javascript object property is undefined

I need help understanding why the following piece of code returns an undefined object property:

var count = 0;
var intervals = {
    collection : []                      
}

intervals.collection[0] = function () {
    this.timer = setInterval(function(){
       count++;
       $("p").html(count);            
    }, 1000);
}();

if(typeof intervals.collection[0] === "undefined") {
    $("span").html("undefined");        
}​

Working Example: http://jsfiddle.net/tvaQk/8/

Basically, I'd like to be able to keep a collection of setIntervals that I can reference later so I can loop through and clear. I was thinking I'd be able to loop through the intervals.collection array and do something like:

clearInterval(intervals.collection[0].timer)

but cannot since intervals.collection[0] is undefined

You forgot the return .

intervals.collection[0] = function () {
  return this.timer = setInterval(function(){
--^^^^^^--

Notice this refers to window , I'm not sure if adding a property timer to the window element is what you were expecting actually. Otherwise, you shall return the interval id to not clutter the global window scope.


A short way to being able to access the timer using intervals.collection[0].timer is by creating an Object instead:

intervals.collection.push({
  timer: setInterval(function(){
    count++;
    $("p").html(count);            
  }, 1000)
});

console.log(intervals.collection[0].timer);

I used Array.push in this example to add the newly created interval as the last element of the array.

Maybe you're complicating things... What I would do is just push the interval straight into the array.

intervals.collection.push( setInterval(function(){...}, 1000) );

You don't need an IIFE to execute the interval, when you push it into the array it'll execute as well.

Then you can clear them all like:

intervals.collection.forEach(function( timer ) {
  clearInterval( timer );
});

You could simply write it like this:

intervals.collection[0] = setInterval(function(){
    $("p").html(++count);            
}, 1000);

You're assigning a self-invoking function, which means you assign the return value of the function. The function itself doesn't return anything therefore it's undefined.

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