Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: get `this` outside the function

Is it possible to get this of a function from outside without calling it in Javascript? I know about the execution context idea, but my logic is, if one can bind this to a function, probably there's a way to fetch it. E.g.:

var a=function(){}; // let's imagine we have a magic function named `getThisFrom()`
getThisFrom(a); // returns `window` (or nothing, because we haven't used `bind()`)

var obj={};
var b=function(){}.bind(obj);
getThisFrom(b); // returns `obj`
like image 783
optimizitor Avatar asked Mar 27 '26 06:03

optimizitor


1 Answers

Before you declare function a you could save this in a variable, i.e. var self = this;. Then return self inside a.

like image 91
C-Otto Avatar answered Mar 28 '26 18:03

C-Otto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!