Nested function inside literal Object
this
refers to d
inside f2
and not object
. You could store a reference to object, or call object
directly, or use call
/apply
to call the function and explicitly tell it what this
means inside that function:
object.d.f2.call(object); // now this refers to object inside f2
Here's an alternative approach which doesn't change the context of this
inside f2()
, based on @slaver113's idea:
var object = (function() {
var _this = {
f1: function() {
alert('This is f1');
},
d: {
f2: function() {
_this.f1();
}
}
}
return _this;
})();
object.d.f2(); // Alerts 'This is f1'