I'm using arrow functions and I'm debugging with Chrome and Firefox Dev Tool. I am getting, this
as undefined, even though the code still works.
For Example: When paused on the following breakpoint, I type this
in the console, and it comes out undefined
, even though the console.log
shows the correct this
:
class A {
f = () => {
debugger;
console.log(this);
};
}
new A().f();
My assumption is, that it has something to do with source-maps.
Here are the tools I use in order to build the my code:
Google ChromeChrome version 45 to 70 supports JAVASCRIPT Arrow functions.
You need to double click the variable name, then right click will reveal the add to watch option.
When using an arrow function, this is not bound to anything and it just inherits from the parent scope which in this case is the window. Adding a console.log (this) before the return in the arrow function returns a Window object, so its looking for Window.food and Window.beverage which will obviously both be undefined.
myOutsideFunction: function myOutsideFunction () { var _this = this; myObject.getMyList (function (myList) { _this.list = myList; }); }, Show activity on this post. If this is undefined within an arrow function, it's undefined outside of the arrow as well. Arrow function simply capture the this of the surrounding scope.
Whenever an arrow function is inside an object, it will derive this value from the enclosing lexical scope. Lexical scope, in this case, is the global scope. this.mom_name in the mother method is equal to the window.mom_name in the web browser. The window.mom_name is undefined by default. Window object doesn’t have the property mom_name.
Arrow functions have no this context, that’s one of the reasons they exist. They use the parent context instead, which in this case is global In objects, rather than writing method: function () {, you can write method() {, they’re the same thing
The problem is that the chrome debugger believes that the this
in the source code refers to the run-time this
, but this
inside a arrow function in typescript source code is actually transformed to _this
, so it's showing you the wrong object.
This is why it's only a problem in the debugger and the code still works fine. When I need to debug something where this is a problem, I just copy it to the console and prepend it with an underscore.
This might be an issue because JS arrow functions don't have this
, the value of this
might be referencing the object containing your arrow function, per Arrow functions revisited and MDN's article on Arrow function expressions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With