Difference between bind and var self=this?
In my react native code, I am using both the bind(this)
and var self = this;
at multiple places across modules.
Both are solving the problem of resolving this
keyword at the right places.
Here are my codes(2 code to perform the same functionality)-
Using
bind(this)
retval.then(function (argument) { console.log("argument"+JSON.stringify(argument)); this.stateSetting(argument); }.bind(this));
Using
var self = this
var self = this; retval.then(function (argument) { console.log("argument"+JSON.stringify(argument)); self.stateSetting(argument); });
Considering they both do the same job, I am curious to know what is the right way to do it? Is there an issue in using one or the other? Or is there a better way to do it?
Answer
Given that you're targeting Node.js which implements ES2015 you are better off using arrow functions.
Arrow functions have what is called a lexicalthis
, which means that the variable this
in an arrow function is treated like a normal variable and will be closed over when you create the function.
So your code becomes:
retval.then((argument) => {
console.log("argument"+JSON.stringify(argument));
// "this" will inherit the value of the outside scope
this.stateSetting(argument);
});
If targeting ES5 (older browsers), then I'd favor the .bind
style rather than var self = this
. It's more structured and closer to a functional approach, which makes the code easier to reason about like you must have discovered by using promises. It also seems to be slightly more performant.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM