Reputation: 7735
var test = {
demo: function(){
//get the caller context here
}
}
//when this gets called, the caller context should be window.
test.demo();
I tried arguments.callee
and arguments.callee.caller
,and no luck...
Upvotes: 52
Views: 38950
Reputation: 531
Strange how we are talking about this
except for
'Qix - MONICA WAS MISTREATED''s comment. Either you are able to capture
window
,self
,v8::Isolate
v8::context
is extended in fetch for cloudflare workers (or use this
of the class
), orthis
-context outside, sothis hypothetical situation has no use case.
var test = {
demo: function(){
//get the caller context here
}
}
test.demo();
For closure, one could have a dynamically named function factory for some reason, while maintaining its context like so:
function body () {}
var test = {
demo: {
[name]: function () {return body.apply(body, arguments);}
}[name];
Without for loop, thisArg
argument would be {demo:fn()}
var test = {demo:{}}
const createNamedFunc = (body) => {
test.demo = return {
[name]: function () {
return body.apply(body, arguments);
} } [name];
}
createNamedFunc(function body (){})
I gather this 'functional-method-parameter-object' is
Upvotes: 0
Reputation: 147363
The value of a function's this
keyword is set by the call, it isn't "context". Functions have an execution context, which includes its this value. It is not defined by this
.
In any case, since all functions have a this
variable that is a property of its variable object, you can't reference any other this
keyword in scope unless it's passed to the function. You can't directly access the variable object; you are dependent on variable resolution on the scope chain so this
will always be the current execution context's this
.
Upvotes: 5
Reputation: 46423
By context, I assume you mean this
? That depends on how the function is invoked, not from where it is invoked.
For example (using a Webkit console):
var test = {
demo: function() {
console.log(this);
}
}
test.demo(); // logs the "test" object
var test2 = test.demo;
test2(); // logs "DOMWindow"
test.demo.apply("Cheese"); // logs "String"
Incidentally, arguments.caller
is deprecated.
Upvotes: 9
Reputation: 12395
Since this
keyword referes to ThisBinding
in a LexicalEnvironment
, and javascript (or ECMAScript) doesn't allow programmatic access to LexicalEnvironment
(in fact, no programmatic access to the whole Execution Context
), so it is impossible to get the context of caller.
Also, when you try test.demo()
in a global context, there should be no caller at all, neither an attached context to the caller, this is just a Global Code, not a calling context.
Upvotes: 53