0

Why does this work:

this.example = element => {
 console.log(element, element, element);
};
this.example.call({}, 'yo');
//prints yo yo yo

As opposed to this:

this.example = element => {
 console.log(element, element, element);
};
this.example.call('yo');
/// prints undefined

I don't seem to understand why the second example prints undefined. Why is it necessary to use a parameter (in this case: an empty object), in order for call to print back our desired solution?

Edit:

For those commenting: it seems that 'this' is ignored during ES6 syntax


example = element => {
 console.log(element, element, element); // yo yo yo
 console.log(this); // {}
};
function example(element) {
 console.log(element, element, element); // yo yo yo
 console.log(this); // {newObjKey: 'value'}
}
example.call({ newObjKey: 'value' }, 'yo');
dumbass
27.2k4 gold badges43 silver badges77 bronze badges
asked Oct 26, 2019 at 18:37
1

2 Answers 2

3

The first parameter of the call method is the this reference the function is bound to. But since it is an arrow function, the first parameter of call is ignored (however, it is still evaluated!). All the other parameters of the call function that follow the this reference are passed as function arguments.

In your first example, {} is ignored and "yo" is passed as a parameter to the example function. In your second example, "yo" is ignored and you didn't provide a second parameter, so by default it's undefined.

answered Oct 26, 2019 at 18:40
Sign up to request clarification or add additional context in comments.

3 Comments

There is no explicit this in arrow function but element must be second parameter of call(). In this case can use anything for first parameter
@charlietfl Even the documentation uses the word ignored. (search for .call()
@charlietfl read my new edit. Seems AlexR is correct. Thanks for both of your help.
0

Call, Apply and Bind methods help to us change this (context) inside function.

Firstly you can't use call, apply, bind with arrow function because arrow function don't have context and inside arrow function this value like get lexically like other variables.

Your first example return "yo", "yo", "yo" because call function's first argument change this's (context) value and other arguments pass like arguments.

In your second example return "undefined" 3x time because you change this's value and U don't pass any argument and if U don't pass any argument parameter's value will be undefined.

answered Oct 26, 2019 at 19:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.