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');
2 Answers 2
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.
3 Comments
this in arrow function but element must be second parameter of call(). In this case can use anything for first parameter.call()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.
call()is thethisArg... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…