The answer is in the question, use a.b.f1()
.
By default, this
refers to the object which owns the function. If the function is "free", this
refers to the global window
object. If this
is not wrapped inside a function, it refers to window
as well.
// "this" is window
function f() { /* "this" is "window" */ }
var o = {};
o.f = function () { /* "this" is "o" */ }
o.child = {};
o.child.f = function () { /* "this" is "o.child" */ }
Knowing this and considering your code, we can say that this
does not refer to a
since it's not contained in a function owned by a
. As a workaround, you could simply replace this
with a
:
var a = {};
a.b = {
f1: function () { console.log('in a.b.f1'); }
};
a.c = {
parent: a,
f2: function () { this.parent.b.f1(); }
};
Notice that you can "redirect" this
to another object using call()
or apply()
:
o.child.f.call(o); // "this" is now "o" inside of "o.child.f"