onclick event executing the same function differently [duplicate] - javascript

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

Related

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.

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

Is there a difference from these 2 functions? [duplicate]

This question already has answers here:
What are the advantages/disadvantages for creating a top level function in ES6 with arrows or without?
(2 answers)
Closed 6 years ago.
I have downloaded an open source js code where the developer often create new function in this way:
var log = msg => div.innerHTML += "<br>" + msg;
So, is there a difference with this below ?
function log(msg){
div.innerHTML += "<br>" + msg;
}
There are some differences between arrow functions and function foo() {} functions. See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions.
A few I can think of off the top of my head:
function foo() {} function definitions are hoisted, which means you can invoke such a function anywhere in the scope that contains its definition. This is not the case for variables containing functions, for which only the declarations are hoisted
Arrow functions bind this lexically, which in simple words means that they do not introduce their own this variable. Instead, they simply close over the nearest this variable from an enclosing scope
Arrow functions do not have the arguments local variable available for use within the body
All that said, the two functions you have shown should behave identically in most cases, given the caveats mentioned above.

ES6 arrow function and this context [duplicate]

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.

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