When you do f.bar2(f.bar1)
, you're passing a reference of bar1 to bar2; inside bar2, it's only known as "func", and the connection with f is lost. The value of this
is determined dynamically when the function is invoked. If you invoke f.bar1(), this will be f, but when you invoke func(), it's undefined, and will fall back to the global object (window).
I have explained this earlier as follows:
The basic rules are, this will be the global object unless:
- the function is called as an object method (then this will be the
object), or
- the function is called as a constructor, with the new
operator (in which case this will point to the new object being
constructed)
One way to avoid that is to create a bound function and pass that:
f.bar2(f.bar1.bind(f));
Note that Function.prototype.bind is not supported by older browsers, so you might need a polyfill (there's one available on MDN).
In the simple scenario you presented, you can do what elclanrs suggests in his comment, as the target this is available inside bar2:
func.call(this);