Code here:
const a = {
target: 'a',
getTarget: () => {
setTimeout(() => {
console.log(this.target)
}, 1000)
},
}
window.target = 'window';
a.getTarget();
I thought it will print 'a', but it turns out to be 'window'.
Code here:
const a = {
target: 'a',
getTarget: () => {
setTimeout(() => {
console.log(this.target)
}, 1000)
},
}
window.target = 'window';
a.getTarget();
I thought it will print 'a', but it turns out to be 'window'.
This is because of the first arrow function you use:
const a = {
target: 'a',
getTarget(){
setTimeout(() => {
console.log(this.target)
}, 1000)
},
}
window.target = 'window';
a.getTarget();// a