Categories
JavaScript

javascript: when scope inside setTimeOut is giving you headaches

Sometimes you have to setTimeOut call a function, but you need to provide the current scope for the function to execute as well.

Say for example, you want to call this.myFunction()

with (this) { setTimeout( function() { myFunction() }, 1000 );}

Doing the with(this) allows you to pass “this” scope, so myFunction will get executed as this.myFunction()

There are a million things wrong with doing the above. First, myFunction will try to execute off the Global, also, with is heavy performance-wise. But it works. Use it sparingly.

Leave a Reply

Your email address will not be published. Required fields are marked *