Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't access variables in another javascript file

So i have link every file needed into the index.html file :

    <script src="jquery.js"></script>
    <script src="notify.js"></script>
    <script src="script.js"></script>

i create an object in 'notify.js' :

    var notify = {
    newNotification : function(text) {
    }
}

script.js :

alert(notify.newNotification);

When i try to access the 'notify' object in 'script.js', it works just fine.But i want to use jquery so i add $(document).ready() to both of the file like this:

notify.js

    $(document).ready (
    function() {
var notify = {
    newNotification : function(text) {
    }
}
}
)

Script.js:

    $(document).ready (
    function() {
alert(notify.newNotification);
    }
)

And after i add that, it comes up with notify is not defined.What's wrong? Can anyone explain why it doesn't work?

like image 803
Haiz Avatar asked Oct 02 '13 02:10

Haiz


People also ask

How is a variable accessed from another file?

The variable number is declared globally and may be accessed from other file when including its declaration with the “ extern ” prefix. However, the variable coefficient is only accessible from the file in which it is declared and only from that point on (it is not visible in function main .

Can one JavaScript file reference another?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.

How do I export a variable to another file in JavaScript?

Use named exports to export multiple variables in JavaScript, e.g. export const A = 'a' and export const B = 'b' . The exported variables can be imported by using a named import as import {A, B} from './another-file. js' . You can have as many named exports as necessary in a file.

How do I include an external JS file in another JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file.


1 Answers

As you have defined var notify in notify.js inside $(document).ready( which is an anonymous function and var notify scope is limited to this function only .

So it is not accessible outside the $(document).ready( function

To make accessible outside don't wrap it in $(document).ready( function

like this:-

var notify;
$(document).ready(function () {
    notify = {
        newNotification: function (text) { }
    }
});
like image 117
Tushar Gupta - curioustushar Avatar answered Sep 30 '22 04:09

Tushar Gupta - curioustushar