1

How to access/get the variable from one javascript file to another javascript file. like first.js contains a function first.js like below.

this.first = function(){
    var x = ['new','old'] 
}

now, I want to access the 'x' in another file say second.js I have tried

var first = require('../first.js');  //path to the first.js file
console.log(first.x)

but getting the undefined value. i want to get/access the 'x' from first.js I am using this for protractor E2E testing using page objects.

5
  • 3
    You need to export any functions or classes you want to use in another file. See here and here Commented Aug 26, 2015 at 6:07
  • 1
    If you have reference to both js files in your page then any global variable value set in one file is available to other file Commented Aug 26, 2015 at 6:12
  • What about using another js file like common.js and use global variable(of course using global in js is not recommended). Another way is, if your 2 file in the same html, we can copy the values through a hidden field. Commented Aug 26, 2015 at 6:12
  • I want to access the variable 'x' in the function first of the first.js file from the second.js file Commented Aug 26, 2015 at 6:18
  • x is local variable to this.first expression make it global or make some method which can return x. Commented Aug 26, 2015 at 6:32

2 Answers 2

2

It doesn't matter on which js files the functions / variables are. After they are parsed, they all belong to the same window.

You get undefined when accessing x property because it is private. x exists only in the local scope of first function.

Here is an example of how you can get access to x.

var first = (function () {
    // private variables / functions
    var x = ['new', 'old'];

    // public properties (properties of "first")
    return {
        getX: function () {
            return x; // x.slice(0); if you want to send a copy of the array
        }
    }
}());
Sign up to request clarification or add additional context in comments.

Comments

1

The module loading system in node.js require you to use module.exports to expose your data types you want to share:

Your example would be re-written as follows:

// first.js

module.exports = {
   x : 'Something here',
   y : 'another item'
};

then on the other file

var first = require('../first.js');  //path to the first.js file
console.log(first.x)

See more details on Node.js module loading system

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.