optimizitor
optimizitor

Reputation: 907

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`

Upvotes: 2

Views: 3245

Answers (2)

Fredrik Borggren
Fredrik Borggren

Reputation: 107

var a = function() { var _b = this; return _b; }

Upvotes: 0

C-Otto
C-Otto

Reputation: 5843

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

Upvotes: 2

Related Questions