最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to force function to create global variable - Stack Overflow

programmeradmin3浏览0评论

How can I force function to create global variable? I have this code:

$.ajax({
  url: '.csv',
  dataType: 'text',
}).done(successFunction);

function successFunction(data) {
  var promenna = data.replace(/\n/g,";").split(";");
  var result = [];
  for (var i = 0; i < promenna.length; i+=2) {
  var line = [];
    line.push(promenna[i]);
    line.push(promenna[i+1]);
    result.push(line);
  }
  for (var i = 0; i < result.length; i += 1){
    $("#tyden" + i + "").append(result[i][0]);
    $("#tyden" + i + "kolik").append(result[i][1]);
  }
}

It loads csv file and create array from it. How can I make the array "line" globaly reachable?

How can I force function to create global variable? I have this code:

$.ajax({
  url: 'https://dl.dropboxusercontent./s/11ofmbg4d4y3gb0/zakaznice_tyden.csv',
  dataType: 'text',
}).done(successFunction);

function successFunction(data) {
  var promenna = data.replace(/\n/g,";").split(";");
  var result = [];
  for (var i = 0; i < promenna.length; i+=2) {
  var line = [];
    line.push(promenna[i]);
    line.push(promenna[i+1]);
    result.push(line);
  }
  for (var i = 0; i < result.length; i += 1){
    $("#tyden" + i + "").append(result[i][0]);
    $("#tyden" + i + "kolik").append(result[i][1]);
  }
}

It loads csv file and create array from it. How can I make the array "line" globaly reachable?

Share Improve this question edited Oct 10, 2016 at 17:25 David R 15.7k8 gold badges58 silver badges74 bronze badges asked Oct 10, 2016 at 16:40 OstrovOstrov 1294 silver badges12 bronze badges 4
  • you mean result? – Malk Commented Oct 10, 2016 at 16:43
  • Declare it outside of your function block. – David R Commented Oct 10, 2016 at 16:43
  • 2 You don't want a global variable. What you want is one initialised outside of the loop, but still in the same local scope. – Bergi Commented Oct 10, 2016 at 16:58
  • i answered this before actually looking at the code.. bergi has a good point. all you need to do is move that variable up 2 lines, before the start of the loop.. – I wrestled a bear once. Commented Oct 10, 2016 at 17:02
Add a ment  | 

3 Answers 3

Reset to default 5

Scope It Outside Function Scope

The most mon approach might be to simply declare it outside of the scope of a function if this is an option :

// This will be globally accessible from any child functions, etc.
var array = [];

function example(){
    // Your code here can access the array as expected
}

Implicit Global Declaration

If you want to declare a variable with global scope, just omit the var when declaring it, which will implicitly create it globally :

function example(){
    // This will be a global variable
    array = [];
}

Note: This will not work within strict mode, which does away with implicit globals. You can read more on about this approach here.

Storing the Variable

Another great approach would be to simply store the object as a property on the window object and access it from there as mentioned in Pamblam's answer.

you can explicitly make any variable "global" by assigning it to the window object.

function things(){
    window.stuff = "junk";
}
things();
alert(stuff);

Despite the fact that what you want is achievable, I do not remend using global variables at all and encourage you to rethink your architecture. Global variables are hard to maintain and can cause errors.


var always creates a variable that has a function scope, so it means it's accessible in the function that it was declared in and all the functions inside that function (unless redefined inside them). If you want to make it global no matter where it is, you have a few options:

Direct assignment to non-existing variable

In case you run your code in non-strict mode, just drop the var. This will cause the lookup of variable line and since it's not declared in any context, it will assign it as a global variable. Example:

function fn() {
    line = 1;
}

fn();
console.log(line); //1

Two drawbacks though:

  • If you ran this code in a strict mode it would cause a ReferenceError
  • If there was a variable with same name in one of the outside functions, it would be overwritten and no global variable would be created

Example:

function outer() {
    var line;
    function inner {
        line = 8; //won't work because there is variable line in some outer context
    }
    inner();
}
outer();
console.log(line); //undefined

Assignment to global object

In every JS execution environment there is something called the global object. If you assign a property to it, you could use it as a global variable (except that it's not a variable - the difference is subtle, but there is). For example:

function fn() {
    window.line = 1;
}

fn();
console.log(line); //1;

This also has some drawbacks:

  • the global object is not necessarily hiding under window variable. In Node it's global and it may vary in other execution environments
  • in case there's a variable with name window (or global) declared on the way, it will override that variable (similar to drawback #2 from previous point)
  • you could use this to access the global object, but only in non-strict mode and only if this wasn't explicitly set (see rules for puting this value)

Indirect eval/new Function

Indirect eval and new Function are always executed as if they were declared directly inside the global scope. Although not elegant and error-prone (you code using strings), they do not suffer from previous drawbacks - work even in strict mode, no matter what variables have been declared on the way and independently from the execution environment. It's simple as that:

'use strict';
function fn() {
    //choose one of the following:
    //indirect eval:
    (0, eval)('line=1');
    //or new Function
    new Function('line=1')();
}

fn();
console.log(line); //1. Works even in strict mode

You may ask "why this weird (0, eval)(...) instead of just eval? That's what called indirect eval, and you can find more info about that under this SO answer


As you see, it is possible. But again, global variables make your code hard to maintain. You should limit the scope of line variable to the area it will be actually used.

发布评论

评论列表(0)

  1. 暂无评论