Container for accessing the internal object

Is there a way for an internal 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 I execute the following code, I get the error message "this.fnc1 is not a function", since this refers to the object t1, and not to the object t.

Is there a way to access fnc1?

+3
source share
2 answers

Of course, if you do not overwrite the variable:

t.fnc1()

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

+2
source

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

Javascript, .
:

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

Source: https://habr.com/ru/post/1729272/


All Articles