2

I've an object, which simplified a bit looks like:

function obj(arg){
    return{
        fct1: function(){
            $(".output").append("called fct1 with arg: "+arg+"<br>");
        },
        fct2: function(){
            $(".output").append("called fct2, which has an other function, which calls fct1<br>");
            fct2a();
            function fct2a(){
                $(".output").append("doing something else, then calling fct1<br>");
                this.fct1(); //not within scope
            }
        }
        }
    }
var myobj = obj("asd");
myobj.fct2();

I want to call fct1 from fct2a, how? Fiddle

2 Answers 2

3

Create a temp var and asign this object to that var and call from that. Please find the code below

function obj(arg){
    return{
        var temp=this;
        fct1: function(){
            $(".output").append("called fct1 with arg: "+arg+"<br>");
        },
        fct2: function(){
            $(".output").append("called fct2, which has an other function, which calls fct1<br>");
            fct2a();
            function fct2a(){
                $(".output").append("doing something else, then calling fct1<br>");
                temp.fct1(); 
            }
        }
        }
    }
var myobj = obj("asd");
myobj.fct2();
Sign up to request clarification or add additional context in comments.

1 Comment

Works if I declare var temp before calling fct2a(). Thank you!
0

You can also declare fct1() separately and invoke it where you need it:

function obj(arg){
    function innerFct1(arg) {
        $(".output").append("called fct1 with arg: "+arg+"<br>");
    }
    return{
        fct1: innerFct1,
        fct2: function(){
            $(".output").append("called fct2, which has an other function, which calls fct1<br>");
            fct2a();
            function fct2a(){
                $(".output").append("doing something else, then calling fct1<br>");
                innerFct1("arg2"); //not within scope
            }
        }
    }
}
var myobj = obj("asd");
myobj.fct2();

1 Comment

what if innerFct1 takes in an arg?

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.