Reputation: 1559
So i was just testing how the value of this
is affected inside an ES6 class method.
Can someone explain me why the value of this
inside the inner function undefined
in below code?
class testingThis {
outerFunc() {
console.log("the value of this in outerFunc: ", this);
function innerFunc() {
console.log("value of this in innerFunc: ", this);
}
innerFunc();
}
};
var newTest = new testingThis();
newTest.outerFunc();
Why is the value this
not preserved in ES6 (not necessarily ES6 i guess) methods but is preserved in usual functions (like below):
function a() {
console.log("this outer: ", this)
function b() {
console.log("this inner: ", this)
}
b();
};
a();
Both inner and outer this
in above code have the same value (window
).
Upvotes: 2
Views: 77
Reputation: 707328
ES6 class are automatically in strict mode.
That means that any plain function call sets the value of this
to undefined
within that function. That's all you're seeing.
FYI, this a strict mode feature, and the only involvement of ES6 is that it automatically puts class definitions into strict mode.
In strict mode, any plain function call sets this
inside that function to undefined
.
When not in strict mode, any plain function call sets this
to the global object which, in a browser, is the window
object.
The new part of your question is two plain function calls, not in strict mode, that both set this
to the global object. It's not "preserving" the value of this
. It's setting it to the global object in both function calls.
Upvotes: 1