This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
What does "this" refer to in arrow functions in ES6?
(10 answers)
Closed 1 year ago.
I'm new to javascript and having trouble understanding the difference between arrow function and normal function when including this keyword, here is the example I read from MDN:
var obj = { // does not create a new scope
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log(this.i, this);
}
}
obj.b(); // prints undefined, Window {...} (or the global object)
obj.c(); // prints 10, Object {...}
In this example arrow function b() can not access i attribute in the object because it references the window
var obj = {
count : 10,
doSomethingLater : function(){ // of course, arrow functions are not suited for methods
setTimeout( () => { // since the arrow function was created within the "obj", it assumes the object's "this"
this.count++;
console.log(this.count);
}, 300);
}
}
obj.doSomethingLater(); //log 11 on the console
However, in the second example, code within the arrow function can access the count attribute. Both functions are defined within the object but only the second function can access the object's attribute, could someone give me some hints why is that? Thanks in advance!
Related
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 1 year ago.
Can someone explain to me why the second function call returns undefined? I see no reason for that. The reference of the object method is stored in a variable, so it should be printed out. Why the result is undefined? The first function call is successful and the only difference is that the second one is stored in a variable.
const module = {
x: 42,
getX: function() {
return this.x;
}
};
//1 - returns 42
console.log(module.getX());
//2 - returns undefined
const unboundGetX = module.getX;
console.log(unboundGetX());
Because unboundGetX function is called by the global window variable, unboundGetX() it's like writing window.unboundGetX() so the this will refer to the global scope which is "window" object so it's also like you wrote return window.x which is logically "undefined".
it will be better to bind your scope to the same object like this :
const module = {
x: 42,
getX: function() {
return this.x;
}
};
console.log(module.getX());
const unboundGetX = module.getX.bind(module); // we bind getX function to module scope instead of the global scope (which is the window variable)
console.log(unboundGetX());
This question already has answers here:
Can you bind 'this' in an arrow function?
(14 answers)
Closed 3 years ago.
function somefunction(cb) {
for(var i=0; i<100000; i++){
}
cb.call({});
};
var a=10;
function test(params) {
somefunction(function () {
console.log(this.a);
});
somefunction(()=>{
console.log(this.a);
});
};
test();
output of the above code is
undefined &
10
I am curious to know when does context binding happened for the arrow function when it printed 10 in the second somefunction call even though i specified different context through bind.
Refer
http://www.ecma-international.org/ecma-262/6.0/#sec-arrow-function-definitions-runtime-semantics-evaluation
In arrow functions, context gets inherited by default, whereas traditional function we have to use .bind(this)
var a=10;
function test(params) {
somefunction(function () {
console.log(this.a);
}.bind(this));
somefunction(()=>{
console.log(this.a);
});
};
test();
This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 3 years ago.
How do I use the variable from the outer scope of the function. I have created this simple example here
var view = {
init(){
const targetOne = document.querySelector(".targetOne");
const targetTwo = document.querySelector(".targetTwo");
var val = "outer scope";
targetOne.addEventListener('click', (e) => {
console.log('target one', val)
});
targetTwo.addEventListener('click', this.handleEvent);
},
handleEvent(e) {
console.log('targetTwo ', val);
}
}
view.init();
JS fiddle link: https://jsfiddle.net/jr7b521x/50/
For the targetOne callback I can use the variable val, but when i define a function for the targetTwo callback, that variable val is not defined in the scope. I feel like I am missing something very simple here, I refreshed on scope chaining and closure but I am not able to get it
the variable val is within the scope of the init () function
for you to get it in the handleEvent function you will need to pass it by parameter or it must be a property of the view object
This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 6 years ago.
I'm reading through the annotated source for the Parsley javascript library, and I keep seeing notations that I don't fully understand. Google searches aren't really helping as google is ignoring "() =>" or "=>" as useful search terms.
Here's an example:
if (event) {
this.submitEvent = $.extend({}, event, {preventDefault: () => {
ParsleyUtils.warnOnce("Using `this.submitEvent.preventDefault()` is deprecated; instead, call `this.validationResult = false`");
this.validationResult = false;
}});
}
I can guess what is happening, but I don't understand the syntax or the name of the function / lambda declaration or pattern.
What is the name of the pattern or style of function declaration? What is its purpose?
These are referred to as arrow functions, which are basically an ES6 approach to leverage functions in a slightly new way. For some simple background on whats going on, MDN explains the idea as such
Two factors influenced the introduction of arrow functions: shorter functions and lexical this.
Check out this example...
var self = this;
setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
}, 1000);
with arrow syntax becomes
// `this` here is the same as `this` in the setInterval
setInterval(() => {
this.age++; // `this` properly refers to this in the outer scope
}, 1000);
So with your example, the "traditional" representation could be as such...
var self = this;
if (event) {
self.submitEvent = $.extend({}, event, { preventDefault: function() {
// [...]
self.validationResult = false;
}});
}
Another great use of arrow functions is for one liners
[1,2,3,4].map(num => num * 2); // [2,4,6,8]
This question already has answers here:
Methods in ES6 objects: using arrow functions
(6 answers)
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 5 years ago.
I am trying to understand arrow functions in ECMAScript 6.
This is the definition I came across while reading:
Arrow functions have implicit this binding, which means that the
value of the this value inside of an arrow function is aways the
same as the value of this in the scope in which the arrow function
is defined!
According to the definition, I believe this for an arrow function should contain the same block level values that the arrow function was defined in.
Code:
var test = {
id: "123123",
k: {
laptop: "ramen",
testfunc: () => console.log(this)
}
}
console.log(test.k.testfunc);
However, I am getting this result from the code
function testfunc() {
return console.log(undefined);
}
What I thought I would get would be an output of:
{"laptop": "ramen"}
if I ran this
console.log(test.k.testfunc());
Let's transform into the equivalent ES5 code:
var test = {
id: "123123",
k: {
laptop: "ramen",
testfunc: function(){return console.log(this)}.bind(this)
}
}
Remember that this depends on how you call the function. The outer this isn't inside a function, so it will default to undefined in strict mode.
Simplified scenario below:
console.log(this) // undefined
var test = {
a: this // same `this` as above
}
You are defining the arrow function in the same scope that you defined var test. If you are defining test in the global scope, then the arrow function's context will be the global scope too.
If you are defining test inside of a method, the arrow function will share the method's context.
function method() {
const self = this;
const test = {
foo: () => console.log(self === this);
}
test.foo()
// console: true
}