3

Is there a way for an inner object (t1) to access its container object.

var t = {
                fnc1: function(){
                    alert("fnc1");
                },
                t1: {
                    fnc2: function(){
                        alert("fnc2");
                    },
                    fnc3: function(){
                        this.fnc1();
                    }
                }
            };
t.t1.fnc3();

when executing the following code i get an error 'this.fnc1 is not a function' since the this is referring to the t1 object and not the t object.

Is there any way to access the fnc1?

Amir
  • 1,219
  • 3
  • 17
  • 31

2 Answers2

2

Sure, as long as you don't overwrite the variable:

t.fnc1()

If you want to call fnc1() as a method of t.t1, use call() or apply().

Christoph
  • 164,997
  • 36
  • 182
  • 240
0

Trying to use Javascript as a pure OO language, drives often to many frustrations.

You could try to use instead the Javascript specific features, mainly functions and closures.
I took you example and made a variant of it:

var t = function(){
    var str = "fnc", 
        fnc1 = function(){
            alert( str + "1");
        };
    return {
        fnc1:fnc1,
        t1:{
            fnc2:function(){
                alert( str + "2");
            },
            fnc3:fnc1
        }
    };
};
t().t1.fnc3();
Mic
  • 24,812
  • 9
  • 57
  • 70