If I have a function like this:
function foo(_this) {
console.log(_this);
}
function bar() {}
bar.prototype.func = function() {
foo(this);
}
var test = new bar();
test.func();
then the test
instance of bar
gets logged.
However, for this to work I have to pass the this
in the bar.prototype.func
function. I was wondering whether it is possible to obtain the same this
value without passing this
.
I tried using arguments.callee.caller
, but this returns the prototype function itself and not the this
value inside the prototype function.
Is it possible to log the test
instance of bar
by only calling foo()
in the prototype function?
You can do this without changing the external function, but you must change the way you call it.
You can't get the context of the caller, but you can set the
this
property on a function you call with the method apply or call. See this reference for an explanation onthis
.Usually if
this
is used, it's in an object oriented context. Trying to call a method of an object with another this might indicate poor design. Explain a bit more what you are trying to achieve for more applicable design patterns.For an example of a javascript OOP paradigm, check my answer here.
I think calling
foo
within the context ofbar
should work:If the question is 'without passing this (by any means)' then answer is no
value can be passed by alternative methods though. For example using global var (within Bar class) or session or cookies.
What about this?
Or this: