0

I apologize, if this is a dublicate, but I can't find the answer I am looking for, although my problem seems to be easy.

This is what I have:

function myMain (myParam) {

    var myObj = {

        myVal1 : 'demo',
        myFunc : function (myParam) {
            console.log (myParam);
        }
    };

    runDemo(myObj);

}

My problem is that I want the console.log to write myParam of myMain, but it is undefined - why?

How can I call myMain('works') so that console writes works?

FYI: runDemo has too be called with this single Object and with myFunc as one of the objects values - no way around that. I am grateful for any help, thanks.

1 Answer 1

1

Make myFunc not take a parameter like so:

function myMain (myParam) {

    var myObj = {

        myVal1 : 'demo',
        myFunc : function () {
            console.log (myParam);
        }
    };

    runDemo(myObj);

}

In this case myFunc retains the value of the variable myParam. This is called a closure.

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

2 Comments

nice, this works - I still do not quite get why, but it does ... thanks for the super fast answer! I will look up 'closure', but feel free to explain further ;)
It is similar to this: var a = 'foo'; function bar(){alert(a);}

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.