1

I have in my HTML file:

<script type="text/javascript">
    var a=2;
</script>
<script src=".../abc.js"/>

What I want to do: inside the abc.js file I want to access the variable a:

#...inside abc.js
function bar(){
    return a; //How?
}

Is this possible/reasonable? No matter how I rephrase my question, I got answers that worked for the other way round, i.e. accessing the external abc.js from within an HTML file...

d.chen
  • 134
  • 5
  • 1
    Aside from using XML-style self-closing tag syntax for the second script, the code you have in the question will already do what you are asking for. – Quentin Jun 02 '14 at 08:17

2 Answers2

1

You can :

1.if a is global :

a=2

and not:

var a=2

2.And a also must be declared outside function specially :anonymous function ,

So don't do this :

(function(){
   var a=2;
})

3.And abc.js should be loaded after . as you had did.

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • 2
    It is declared outside of any function, it is already a global. You don't need to omit the `var` statement. – Quentin Jun 02 '14 at 08:16
  • worked! either with or without 'var', although IDE complains about not resolving the variable name. – d.chen Jun 02 '14 at 08:36
0

This in your abc.js

function bar(var1){
result = var1; //do other stuff here
return result;
}

and this in your HTML

<script src="abc.js"></script> 
<script>
//invoke the bar function and pass it info
var luckynumb = bar(7); //now luckynumb is 7
</script>
Pellmellism
  • 380
  • 1
  • 11