0

I have the next in JS:

function doC() {
    this.try = document.getElementById("try");


function tryC(){

       //do something
    }
}

Now, I want to call tryC function, when so I wrote the next:

<script type="text/javascript" src="myFile.js"></script>
<script type="text/javascript">tryC();</script>

But as I see, nothing happen. Ho I call tryC()?

Tom Avni
  • 109
  • 3
  • 9

2 Answers2

3

You have defined C in the scope of doC. It is not accessible outside of doC.

If you want it to be accessible globally, then you have to explicitly assign it a global.

window.C = function () { /* etc */ };

Creating globals is usually a bad idea, more so when they aren't created at load time. There is probably a better way to achieve whatever problem you are trying to solve with this.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Your tryC is defined inside doC, it's not exposed (it's private), you can do:

   function doC() {
        this.try = document.getElementById("try"); 

        return function(){
           alert('Try C');
        }
    }

    doC()(); // alerts

or

function doC() {
    this.try = document.getElementById("try"); 

    return {
        tryC : function(){
                  alert('Try C');
               }
    }
}

doc().tryC(); //alerts

Or your way (globals all around)

    function doC() {
            this.try = document.getElementById("try"); 

            this.tryC = function(){
               alert('Try C');
            }
    }

doC(); // call first!
tryC(); // alerts
kayz1
  • 7,260
  • 3
  • 53
  • 56