Skip to content

Instantly share code, notes, and snippets.

@sematgt
Created January 13, 2021 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sematgt/cfda42d8ed4bd2662ad66fab1e35fc09 to your computer and use it in GitHub Desktop.
Save sematgt/cfda42d8ed4bd2662ad66fab1e35fc09 to your computer and use it in GitHub Desktop.
// если в колбеке setTimeout используем this, то нужно либо привязка bind, либо стрелочная функция,
// так как setTimeout вызывает колбек в другом контексте и this внутри функции будет глобальным объектом
// wrong
var obj = {
count : 10,
doSomethingLater : function (){
setTimeout(function(){ // the function executes on the window scope
this.count++;
console.log(this.count);
}, 300);
}
}
obj.doSomethingLater(); // console prints "NaN", because the property "count" is not in the window scope.
// right
var obj = {
count : 10,
doSomethingLater : function(){ // of course, arrow functions are not suited for methods
setTimeout( () => { // since the arrow function was created within the "obj", it assumes the object's "this"
this.count++;
console.log(this.count);
}, 300);
}
}
obj.doSomethingLater();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment