0

I have this HTML document:

<!DOCTYPE html>
<html>
    <body>
        <script type="text/javascript" src="/first.js"></script>
        <script type="text/javascript" src="/second.js"></script>
    </body>
</html>

first.js:

(function(){
    var p = 9;
    ...
})();

How to have access and edit the p variable from second.js without modifying first.js? Is there a way?

ZTTR
  • 25
  • 7
  • You should see [this question](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript). – Serge K. Sep 05 '17 at 09:33

3 Answers3

0

You can make your variable global using :

(function(){
    window.p = 9;
    ...
})();
Nolyurn
  • 503
  • 2
  • 13
0

Set p as global variable in first.js

var p;
(function(){
   p = 9;
    ...
})();
Stéphane Ammar
  • 1,394
  • 7
  • 16
0

export your variable

(function(exports){
   exports.p = 9;
    ...
})(window);
viola
  • 50
  • 6
  • While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion – Prashant Tukadiya Sep 05 '17 at 10:10