this.emit() in an arrow function [duplicate] - javascript

This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 6 years ago.
Trying to figure out how to do an arrow function while maintaining this.emit(). In gulp and ES6 I have a function like so:
gulp.src([paths.sass])
.pipe(sourcemaps.init())
.pipe(sass().on('error', function (e) {
reportError(e);
this.emit('end');
}))
Notice the usage of this.emit('end'). Works great when I use a non arrow function, but the second I do:
gulp.src([paths.sass])
.pipe(sourcemaps.init())
.pipe(sass().on('error', (e) => {
reportError(e);
this.emit('end');
}))
this.emit('end') is no longer available. How could I write that function using an arrow function and maintain the this.emit()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
in arrow function of ECMAScript2015, this always referencing outside function, no runtime context.
meaing:
function out() {
var name = "out"
return function() {
return function() {
return function() {
console.log(this.name) // out
}
}
}
}
arrow function no Object arguments
arrow function can't using yield
arrow function can't initialized by new

If the on method of the sass() returned object arranges to call the supplied function as a method of another object, and the function needs to pick up the value of the object it is called on, in order to call its emit method, use the function declaration.
Arrow functions avoid using
Function.prototype.bind on the current this value of the defining context, by always using the defining context's this value inside the function. Another aspect of arrow functions is that they can't be used as constructors. Arrow functions do not deprecate function declarations and expressions and should only be considered "preferable" on a case by case basis.

Related

onclick event executing the same function differently [duplicate]

This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 3 years ago.
I have a test function:
function test(element) {
console.log(element.id);
console.log(element);
}
which I want to use as a callback when my button <button id="testbtn">afsdasd</button> is pressed. If I do this:
document.getElementById('testbtn').onclick = () => {
test(this);
};
I get the following output:
However, if I do this:
document.getElementById('testbtn').onclick = function() {
test(this);
};
the output is different:
Why? I thought both versions were exactly the same?
The first one is an arrow function while the second one is a regular function. Arrow functions do not have their own this binding, so they will search this in the next outer lexical scope. In your case the enclosing lexical scope for the arrow function is the Window object.
An arrow function does not have its own this. The this value of the
enclosing lexical scope is used; arrow functions follow the normal
variable lookup rules. So while searching for this which is not
present in current scope, an arrow function ends up finding the this
from its enclosing scope. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Behaviour Difference For Arrow-Functions vs Functions In Javascript [duplicate]

This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 4 years ago.
I wanted to understand the behavior of a normal function vs arrow functions.
Arrow Function:
function arrowFunc() {
return () => arguments
}
console.log(arrowFunc(1, 2, 3)(1))
Normal Function
function normalFunc() {
return function() {
return arguments
}
}
console.log(normalFunc(1, 2, 3)(1))
Both the results are expected to be same, but looks like arrowFunc defined above considers the first arg list, where as the normalFunc considers the second set of arg list.
Also tried babel-compilation to understand the difference, but looks like the behavior is different as shown below:
Babel Output:
"use strict";
function arrowFunc() {
var _arguments = arguments;
return function() {
return _arguments;
};
}
console.log(arrowFunc(1, 2, 3)(1));
function normalFunc() {
return function() {
return arguments;
};
}
console.log(normalFunc(1, 2, 3)(1));
Both the results are expected to be same
No, they're not.
From the first line of the MDN page on arrow functions (emphasis mine):
An arrow function expression has a shorter syntax than a function
expression and does not have its own this, arguments, super, or
new.target.
And further down the same page:
Arrow functions do not have their own arguments object. Thus, in
this example, arguments is simply a reference to the arguments of the
enclosing scope [...]
And in the ECMAScript specification:
NOTE: Arrow functions never have an arguments objects. (sic)

Arrow function would change the context of this [duplicate]

This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 5 years ago.
Is it by design that arrow functions can redefine existing functions behavior? Using jQuery's get (yes, I know) - I'm getting two different values of this inside success depending on whether arrow function is used or not. Can anyone explain why it happens?
var get = (e) => {
return new window.Promise((resolve, reject) => {
$.ajax({
context: {test: 1}, // this
type: "GET",
url: "...",
complete: function () {
// this is only correct when using old syntax, arrow
// function would redefine the value of this to the function's parent
},
complete: ()=>{ } // Is not working, this is not what I'd expect.
});
});
Arrow functions were primarily introduced to change the scoping of this which helps to avoid using .bind(this) all the time. It's natural that you get different values
From MDN: Arrow Functions
An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target.
The cleaner, more succint syntax is of secondary value. They are certainly not an absolute replacement for function
Now that this is taken out of the equation - you've also got 2 oncomplete callbacks in your example.

Passing this from .call() to arrow function [duplicate]

This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 5 years ago.
I have an arrow function that I am trying to execute with call(). For the sake of simplification, as follows:
Operational as expected
const func = (e) => {
console.log(e)
}
func.call(null, e)
Hmm ... what's going on here?
I would expect the following code to pass element into func as this.
const func = (e) => {
console.log(this)
console.log(e)
}
func.call(element, e)
But, instead this remains undefined.
If I switch it to a regular function definition, all works as expected.
const func = function (e) {
console.log(this)
console.log(e)
}
func.call(element, e)
Question
Why am I not able to pass a context for this into an arrow function from call()?
this is not bound in arrow functions, so call() and apply() can only pass in parameters. this is ignored
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Invoked_through_call_or_apply
In ES6 this has lexical scope meaning value of this inside arrow function would be same as that outside of arrow function. In pre-ES6 form this is the object that you passed as a first argument to call method.

Using fat arrow syntax for event handlers in javascript doesn't work [duplicate]

This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 6 years ago.
I have some input elements to which I want to attach event listeners on the change event like so:
inputs.forEach(input => input.addEventListener('change', handleUpdate));
Now the handleUpdate handler function works when defined as a named function like this:
function handleUpdate() {
console.log(this.value);
}
But this doesn't work when used with the fat arrow syntax like this:
const handleUpdate = () => console.log(this.value)
Now I know that this is set to the window object and one way to fix this is:
const handleUpdate = (ev) => console.log(ev.target.value);
But is this the right way to use fat arrow syntax in Javascript for event handlers or is it not recommended to use them in the first place?
es6 fat arrow notation maintains the value of "this" to the context where the function is created. If you want to change the value of "this" inside the function you should use "bind" on the function.
And
const handleUpdate = () => console.log(this.value)
is not an anonymous function. It's a function called "handleUpdate". An anonymous function is a function that does not have a name assigned so you cannot call it execpt using it in the context it's defined. Example
target.addEventListener('click', () => { doSomeStuff() };
So your question does not compute in the context of the code you're posting.
Edit bind usage:
var handleUpdate = function() {console.log(this.value)};
handleUpdate = handleUpdate.bind(whatever_you_want_this_to_mean_inside_the_function);
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
The methods call(), apply(), and bind() will not change the value of this in arrow functions. (In fact, the value of this inside of a function simply can’t be changed–it will be the same value as when the function was called.) If you need to bind to a different value, you’ll need to use a function expression.

Categories