0

well i need to call a function defined in another javascript file(file 2) in file 1. i just wrote in file 1

var ball;
var ab=document.getElementById("abcd");
funcname();

now in the other file(file 2)

function funcname()
{
    ball=ab.width; //line 2
}

now it shows an error like cannot find ab when it comes to line 2

i cant understand why this happens... and i tried this and this worked

in file 1

 var ball;
    var ab=document.getElementById("abcd");
    funcname(ball,ab);

in the other file (file2)

function funcname(ball,ab)
    {
        ball=ab.width; //line 2
    }
TylerH
  • 20,799
  • 66
  • 75
  • 101
  • When you call funcname() it has no idea what ab is because that is defined in a different function and is out of context. If you want access to ab in your 2nd function you must pass it as a parameter like you have – CSharper Mar 03 '14 at 16:26
  • 1
    http://stackoverflow.com/questions/950087/how-to-include-a-javascript-file-in-another-javascript-file?rq=1 – fiction Mar 03 '14 at 16:26
  • is there no other way other than using them as parameters – user3375632 Mar 03 '14 at 16:45

1 Answers1

0

In first example of File2, ab is undefined because you instanciated it in another file (file2 can't use variables/functions defined in file1).

In second example you pass it in parameter of the function and that's the reason why the function can use it.

And pass ball in parameter of the function for setting it a value after is useless !

JGeo
  • 380
  • 13
  • 33
  • so is there no other way than passing them as parameters( i am not talking about ball) – user3375632 Mar 03 '14 at 16:44
  • You can include the file with one of the solutions given by the link of user3362707 in your first post. Passing parameters is a problem for you ? – JGeo Mar 03 '14 at 16:46
  • I just wanted to know too... You have now the solutions to solve your problem, right ? – JGeo Mar 03 '14 at 16:52