The this keyword does suck. Your friend is totally right lol. This is why you might see const self = this; in some JS and see self used more.
this
const self = this;
self
const self = this is not solving the problem that this could be bound ambiguously. It is simply solving the problem where each function would have their own this. E.g.
const self = this
function
function a () { const self = this; return function() { return self.x; } } a.call({ x: 3 })(); // 3
I like using bind to solve this problem tho:
function a () { return (function() { return this.x; }).bind(this); } a.call({ x: 3 })(); // 3
But of course the nicest way would be using arrow functions:
function a () { return () => this.x; } a.call({ x: 3 })(); // 3
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
The
thiskeyword does suck. Your friend is totally right lol. This is why you might seeconst self = this;in some JS and seeselfused more.const self = thisis not solving the problem thatthiscould be bound ambiguously. It is simply solving the problem where eachfunctionwould have their ownthis. E.g.I like using bind to solve this problem tho:
But of course the nicest way would be using arrow functions: