Skip to content

Instantly share code, notes, and snippets.

@noodle71
Created April 3, 2019 12:50
Show Gist options
  • Save noodle71/c59934fbf8828a403ef6c7a397df7dc1 to your computer and use it in GitHub Desktop.
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"
//////////////////////// 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