I found that 'this' keyword seems always point to global
in using arrow function inside a nested object literal.
According to other questions, the following snippet can be explained as an arrow function's 'this' is defined in lexical context.
var c = 100;
var a = {c:5 , fn: () => {return this.c;} };
console.log(a.c); //100
However, I cannot understand the following code (nested object literal):
var c = 100;
var a = {
c: 5,
b: {
c: 10,
fn: ()=> {return this.c;}
}
}
console.log(a.b.fn());// still 100, why not 5?
I mean, if consider from the lexical context aspect, shouldn't the 'this' in a.b.fn point to a?
Why, no matter how many levels the object is nested, do all of the 'this' instances point to window or global?
The only expression in JavaScript that changes scope is a function and, as of ES6, blocks (note that an object literal is not a block, despite having curly braces around it). This means: everything that is not inside a function is in global scope.
In global scope, this
refers to the global object (window
in case of browsers). The only thing that changes scope is the arrow function (yes, they DO change scope!) - but it binds this lexically (which means, it uses the this
from the outer scope), so it's still the global object.
If you want this
to refer to the a
object, use an IIFE instead of an object literal:
var c = 100;
var a = new function () {
this.c = 5;
this.b = {
c: 10,
fn: ()=> {return this.c;}
}
}()
alert(a.b.fn()) // 5;
Or, to bind b
to this
:
var c = 100;
var a = {
c : 5,
b : new function () {
this.c = 10;
this.fn = ()=> {return this.c;}
}()
}
alert(a.b.fn()) // 10;
Alternatively, to bind this
to b
, you can also use a regular function instead of the arrow function:
var c = 100;
var a = {
c: 5,
b: {
c: 10,
fn: function () {return this.c;}
}
}
alert(a.b.fn()) // 10;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments