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?

2 Answers 2

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().

Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.