Last active
December 7, 2018 06:57
-
-
Save hongkheng/ec61e8da5f15c75b402a0c580c1686b5 to your computer and use it in GitHub Desktop.
Regarding `bind` in constructor for class methods
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
// Bind class methods that would be call externally by when executing `new Foo()` | |
// context to `this` for the current class context will be lost when assigning the method to another object | |
// e.g | |
// Binding a method as an instance property | |
class Bar { | |
constructor() { | |
//this.bar = this.bar.bind(this); // <-- this line is required when obj reference is being passed around such that the context of `this` is lost | |
this.counter = 0 | |
} | |
bar() { | |
this.counter++ | |
console.log('bar', this); | |
} | |
that() { | |
this.bar() | |
} | |
} | |
var bartop = new Bar() | |
const barsss = bartop.bar | |
console.log('barss', barsss); // runtime error due to `counter` is not defined when this.bar = this.bar.bind(this); is commented out | |
// Cases when .bind(this) is needed | |
function passFnByRef(fnRef) { | |
fnRef() // when you need to pass a function as an argument and execute it at a point | |
// if you did not do a `.bind(this)` in the constructor method when you call the function, | |
// context of `this` will be `undefined` or `window`. And methods call with `this.` will complained | |
// `undefined` | |
} | |
// Applies to ES7 class fields / ES6 class / ES5 prototypal inheritiance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment