JS Through2 Arrow Function This.push()
I have a problem with lexical binding in JavaScript. This is my code:
.pipe(through.obj((url, enc, done)=>{
if(!url) return done();
request.head(url, (err, response)=>{
this.push(url + ' is ' + (err ? 'down' : 'up') + '\n');
done();
});
}))
I get this error:
TypeError: this.push is not a function
But when I use es5 function syntax like function(url,enc,done){...}
:
.pipe(through.obj(function(url, enc, done){
if(!url) return done();
request.head(url, (err, response)=>{
this.push(url + ' is ' + (err ? 'down' : 'up') + '\n');
done();
});
}))
then my code works well.
In this case, how can I use this.push() with the Arrow Function?
I know about Arrow Function's lexical binding, but I have no idea about using this
.
Thanks for reading my text.
Answer
Well in the former case, your this
is pointing to window
object. That's why you're getting the error.
arrow
functions don't provide their own this
binding (they retain the this value of the enclosing lexical context)
In arrow functions, this retains the value of the enclosing lexical context's this. In global code, it will be set to the global object:
var globalObject = this; var foo = (() => this); console.log(foo() === globalObject); // true
Check this out MDN-this particularly Arrow functions Section
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