[英]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/ 工作示例: 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. 基本上,我希望能够保留一个setIntervals集合,以后可以引用该集合,以便我可以遍历和清除。 I was thinking I'd be able to loop through the intervals.collection array and do something like: 我以为我可以遍历interval.collection数组并执行类似的操作:
clearInterval(intervals.collection[0].timer)
but cannot since intervals.collection[0]
is undefined 但由于intervals.collection[0]
未定义而不能
You forgot the return
. 你忘了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. 请注意, this
是指window
,我不确定向window
元素添加属性timer
是否是您真正期望的。 Otherwise, you shall return the interval id to not clutter the global window
scope. 否则,您应返回间隔ID,以免使全局window
范围混乱。
A short way to being able to access the timer
using intervals.collection[0].timer
is by creating an Object instead: 使用intervals.collection[0].timer
可以访问timer
一种简短方法是创建一个Object:
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. 在本示例中,我使用Array.push
将新创建的间隔添加为数组的最后一个元素。
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. 您不需要IIFE来执行间隔,当您将其推入数组时,它也会执行。
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. 该函数本身不返回任何内容,因此未定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.