ES6 arrow function and this context [duplicate] - javascript

This question already has an answer here:
Arrow Function in Object Literal [duplicate]
(1 answer)
Closed 6 years ago.
I have read some topics on arrow function, but below code just confuses me.
var bunny = {
name: 'Usagi',
tasks: ['transform', 'eat cake', 'blow kisses'],
first : () => {
console.log(this) //does not refer to bunny
},
second: function(){
console.log(this) //refers to bunny
},
third() {
this.tasks.forEach((task) => {
console.log(this); //refers to bunny
});
}
};
bunny.first();
bunny.second();
bunny.third();
Can anyone tell me how come third function inner function this refers to current object, while the first one does not. Is it not when we use arrow function, this refers to current scope where it is defined?

Arrow functions are more or less equivalent to function statements, except that they bind the this argument to that of the parent scope.
In other words, if an arrow function appears in the top scope, its this argument will always refer to the global scope (e.g., window in browsers or global in node.js), while an arrow function inside a regular function will have its this argument the same as its outer function, as your code demostrates.

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

Why is 'this' in JavaScript refer to different context in the examples? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
scope of the object literal methods
(3 answers)
Closed 4 years ago.
I am quite new to JavaScript, I am really confused by the below two examples of 'this', on what 'this' is bound to and why:
Example 1:
function Person(age) {
this.age = age;
this.growOld = () => {
this.age++;
}
}
var person = new Person(1);
setTimeout(person.growOld,1000);
Example 2:
var Actor = {
name: 'RajiniKanth',
movies: ['Kabali', 'Sivaji', 'Baba'],
getName: () => {
alert(this.name);
}
};
Actor.getName();
Why even though both examples use arrow function, but 'this' is bound to different context?
A method inside an object using an arrow function this will bind to the object, if if not inside an object this refers to the global scope, even if encapsulated by another method.
The keyword this has different meanings in function expressions and function declarations.
Arrow functions are expressions. Accordingly, this is bound to a lexical context.
See MDN this

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.

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.

could you explain the function in javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
(function(){
var foo = 'Hello world';
})();
i don't know what's use of it? and what's meaning of it/?
On its own it does nothing except declare a variable that isn't used - it should invoke some other functions to do something useful.
That said, what you have is an immediately invoked function expression, i.e. an anonymous function:
function() { ... }
which is invoked with no parameters:
(f....)();
The rationale is two fold:
it allows the function to be defined and called without giving it a name in the global name space
any variables defined within the function are also held within that scope, and don't pollute the global name space.
It's an anonymous function that executes immediately.
The idea is to create a private scope. Often one would return a closure from the anonymous function that retains access to variables created in that scope.
For example
var greet = (function () {
var foo = 'Hello world';
return function () {
alert(foo);
}
}());
greet();
This calls an anonymous function immediately.
Have a look here: What does this “(function(){});”, a function inside brackets, mean in javascript ?

Categories