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

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.

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

Is there a way to call an Arrow Function just after it has been declared? [duplicate]

This question already has answers here:
ES6 immediately invoked arrow function
(4 answers)
Closed 4 years ago.
Sometimes I want to assign a variable the result of an Arrow function, but if I assign the Arrow Function to that variable it get the function and not the return of that Function as is obvious.
let theNumber2 = ()=>{return 2};
theNumber2 will contain the function and only if I do theNumber2() I will get returned 2.
Is there a way to do something like this to get directly the return of the arrow function? For example:
let theNumber2 = ()=>{return 2}(); // Note the () at the final
Does there exist something to do that? I mean, to assign the arrow function called?
Just wrap in parenthesis and call the function.
let theNumber2 = (() => { return 2; })();
console.log(theNumber2);

replace the use of function declaration when using es6/es7 [duplicate]

This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 4 years ago.
I prefer do function declaration
doSomething() //still works
function doSomething() {}
over
var doSomething = function() = {}
doSomething()
because with the function declaration, I don't have to worry about the order, it just got hoisted at the top. Now when it come to es6, my coworker like to do const doSomething = () => {} because for them they dislike the word 'function'. I lost the hoisting how can I fix it?
I hope I can do this
abc()
abc() => {}
but I have to use babel so that the word function can be ignore to make a function in es6/es7?
No you can't:
abc();
abc() => {console.log('test');}
Moreover, arrow functions do now have their own this context and cannot be used as constructors. Which means they are not only for people who do not want to use the function keyword.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

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.

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