Reputation: 934
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // this refers to the person object
}, 1000);
}
But what if I want to access the "this" of the setInterval function, instead of the parent object. I know arrow functions don't have a lexical this of their own, but is there a way to circumvent this, other than writing a non-arrow function?
Upvotes: 0
Views: 370
Reputation: 11585
No, the arrow function does not possess athis
variable (nor argument
, super
& new.target
) so there is nothing to "circumvent" to.
An arrow function is designed to inherit lexical scope, if it did have its own this
- it would interfere with its defining behavior.
Don't think about arrow functions as a nice shorthand for a regular function.
Instead, you should "read" arrow functions as:
...execute these statements in the surrounding context...
and
...this function does not have the mental overhead of tracking which, of the 4 patterns of invocation, are being used to determine the value of
this
)
Upvotes: 4
Reputation: 28722
The this
of setInterval()
= window
.
If you have strict mode enabled in your script (something like 'use strict';
at the start of your script) it will be undefined
. For all intents and purposes you might wish to use the global scope of window
You can rewrite your function to access window like this:
setInterval(() => {
this.age++; // this refers to the person object
window.something = this.age;
}, 1000);
Also, you're not saving the setInterval ID so you can't clear it when the object is obsolete. It will remain in memory causing you potential memory leaks
function Person(){
this.age = 0;
this.kill = function() {window.clearInterval(this.interval);};
this.interval = setInterval(() => {
this.age++; // this refers to the person object
}, 1000);
}
So that when a Person is obsolete, you can kill() them, leaving no traces of them.
Upvotes: 1
Reputation: 664620
Is there a way to circumvent this, other than writing a non-arrow function?
No.
The this value that is passed into an arrow function is ignored by it and not available in any form.
Upvotes: 5