Arrow function would change the context of this [duplicate] - javascript

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.

Related

Are these 2 JavaScript statements equivalent? [duplicate]

This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
What are the advantages/disadvantages for creating a top level function in ES6 with arrows or without?
(2 answers)
Closed 1 year ago.
These 2 statements seem to do the same thing.
const handleClick = () => alert('foo');
and
function handleClick() {
alert('foo');
}
Are they identical and just syntactically different? The first one looks like a variable declaration, whereas the second one is clearly a function definition.
No, they are not the same thing. The arrow function has some limitations:
Does not have its own bindings to this or super, and should not be
used as methods.
Does not have new.target keyword.
Not suitable for
call, apply and bind methods, which generally rely on establishing a
scope.
Can not be used as constructors.
Can not use yield, within its
body.
ES6 arrow functions provide you with an alternative way to write a shorter syntax compared to the function expression. There is no performance difference.
Are arrow functions faster (more performant, lighter) than ordinary standalone function declaration in v8?

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)

what is the use of arrow functions in reactJS? [duplicate]

This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 4 years ago.
does it help in handling the this keyword sometimes, when compared to the normal functions like in ReactJS?
Because in react to pass functions through components we need consider the this keyword very carefully so please help me understand how arrow functions help.
Arrow functions lack scope. For example:
function outer()
{
function inner()
{
console.log(this) //Refers to inner function
}
inner();
}
function outerTwo()
{
let inner = () => {
console.log(this) //refers to outer
}
inner();
}
outer();
outerTwo();
If you try to use an arrow function for a prototype method definition and you use thisanywhere in there, it'll refer to the window / global context.Because it will not have it's own scope. Because they lack scope, they can be useful for method injection, where they can refer to the the container that's calling them. Hence, why they're often used as callbacks.
You answered the question yourself. Using arrow function helps you with referencing this context of the given component and sometimes is also used as it is shorter and therefore faster to write.

What is the difference between () => {} and function() {} in react-native javascript? [duplicate]

This question already has answers here:
What are the differences (if any) between ES6 arrow functions and functions bound with Function.prototype.bind?
(3 answers)
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 6 years ago.
I have seen some functions defined as function(){} and some functions defined as () => {}.
Is this related to Javascript version ES6?
Also, how does use of this keyword change from one function definition to another?
The () => {} is called an arrow function. They are, as you said, part of ES6. From the linked page:
An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous.

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

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.

Categories