Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
brandonlind2
7,823 PointsDoes anyone know why this method is returning NaN?
let count= {
amount: 0,
count: function(){
this.amount++
console.log(this.amount);
},
start: function(num){
setInterval(this.count,num)
}
}
if i were to run count.start(500); it would return not a number
1 Answer
Thomas Nilsen
14,957 PointsBecause
start: function(num){
setInterval(this.count,num)
}
the keyword 'this' inside setinterval is no longer pointing to your object, but the window-object.
One option would be to use the bind function like this
let count= {
amount: 0,
count: function(){
this.amount++
console.log(this.amount);
},
start: function(num){
setInterval(this.count.bind(this),num)
}
}
count.start(500);
brandonlind2
7,823 Pointsbrandonlind2
7,823 Pointsthanks!!