Created
January 13, 2021 09:49
-
-
Save sematgt/cfda42d8ed4bd2662ad66fab1e35fc09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// если в колбеке 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