Keith
Keith

Reputation: 26489

How to access variable inside another function

I have a function to calculate the screen width

var screenWidth = jQuery(window).width();

function checkScreenSize()
{   
    screenWidth = jQuery(window).width();
}

jQuery(window).on("resize", checkScreenSize).resize();  

How can I use this screenWidth inside another function?

EDIT:

I want to access this variable here, for example:

function showContent() {
    if(screenWidth <= 1000)
    {
         console.log(screenWidth);
    }
}

Upvotes: 0

Views: 1454

Answers (4)

user4244405
user4244405

Reputation:

You can achieve this by defining said variable in global scope; if that var screenWidth = ... is defined inside some other function context you will not have access to it from other functions.

Using globals is a bad idea; however, in many cases you need some variable value that you need access to from other places. In this case, you could construct a well defined "Globals" container, like i.e:

'use strict';        // strict mode    :: prevents nasty bugs
this.Main = this;    // super-global   :: refers `window` -or- `global`

Main.Globals = {screenWidth:null};

// your dynamic screen resizing code here sets the `Globals.screenWidth`
// now you have access to this anywhere

You can also write some code to have this Globals object be only writable by certain functions, but this technique is probably out of the scope of this question; however it could be a good idea considering that this code is part of a large project with many collaborators in your team.

Upvotes: 0

Komeil Tl
Komeil Tl

Reputation: 24


when you defined variable out of function , it will be global variable and you can use it in other function !!
do you have problme with this ?


you can also visit : http://www.w3schools.com/js/js_scope.asp

Upvotes: 0

maioman
maioman

Reputation: 18734

Your global screenWidthis quite useless...

if you need to know the width inside the resize handler callback that's where you need to call jQuery(window).width()

function checkScreenSize(){
  var w = $(window).width()
  console.log(w)
}

jQuery(window).on("resize", checkScreenSize)

// .resize() is a shorthand for .on('resize' method
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76426

Since screenWidth is a global variable declared outside the function you have mentioned, you can access it as it is:

function foo() {
    console.log(screenWidth);
}

Upvotes: 1

Related Questions