Created
April 3, 2019 12:50
-
-
Save noodle71/c59934fbf8828a403ef6c7a397df7dc1 to your computer and use it in GitHub Desktop.
Trying to call a method within a closure without binding the initial context can lead to change the value of "this"
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
//////////////////////// NOT WORKING: CASE 1 //////////////////////// | |
class ClosureMethodWithoutBind{ | |
constructor(prop){ | |
this.prop = prop; | |
} | |
changeAfter(cb, milis){ | |
setTimeout(cb,milis); | |
} | |
emptyProp(){ | |
this.prop = ''; | |
} | |
emptyPropAfter(milis){ | |
this.changeAfter(this.emptyProp, milis); | |
} | |
log(){ | |
console.log('prop: %s', this.prop); | |
} | |
} | |
var c1 = new ClosureMethodWithoutBind('Angel'); | |
c1.log(); | |
// console -> prop: Angel | |
c1.emptyPropAfter(100); | |
setTimeout(() => c1.log(), 200); | |
// console -> prop: Angel | |
//////////////////////// WORKING: CASE 2 //////////////////////// | |
class ClosureMethodWithBind{ | |
constructor(prop){ | |
this.prop = prop; | |
this.emptyProp = this.emptyProp.bind(this); | |
} | |
changeAfter(cb, milis){ | |
setTimeout(cb,milis); | |
} | |
emptyProp(){ | |
this.prop = ''; | |
} | |
emptyPropAfter(milis){ | |
this.changeAfter(this.emptyProp, milis); | |
} | |
log(){ | |
console.log('prop: %s', this.prop); | |
} | |
} | |
var c2 = new ClosureMethodWithBind('Angel'); | |
c2.log(); | |
// console -> prop: Angel | |
c2.emptyPropAfter(100); | |
setTimeout(() => c2.log(), 200); | |
// console -> prop: | |
//////////////////////// WORKING: CASE 3 //////////////////////// | |
class ClosureMethodWithImplicitBind{ | |
constructor(prop){ | |
this.prop = prop; | |
} | |
changeAfter(cb, milis){ | |
setTimeout(cb,milis); | |
} | |
emptyProp = () => (this.prop = ''); | |
emptyPropAfter(milis){ | |
this.changeAfter(this.emptyProp, milis); | |
} | |
log(){ | |
console.log('prop: %s', this.prop); | |
} | |
} | |
var c3 = new ClosureMethodWithImplicitBind('Angel'); | |
c3.log(); | |
// console -> prop: Angel | |
c3.emptyPropAfter(100); | |
setTimeout(() => c3.log(), 200); | |
// console -> prop: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment