简体   繁体   中英

Javascript: Get scoped variable

I'm writing a counter to count an object, and it looks like this:

function myFunc(param) {
  this.param = param;

  param.foo = function() {
    var object = window.JSON.parse(data);
    for (i in object) {
      counter++;
    }
  }

}

var foo = new myFunc('data.json');
var counter = 0;
document.write(counter); // displays 0

How can I achieve to get the counter value outside the function? I tried almost everything, from window to return to separate functions .

Any clue?

Update

I prefer a better design like this

function myFunc(param) {
  this.param = param;

  param.foo = function() {
    var object = window.JSON.parse(data);
    var counter = 0;
    for (i in object) {
      counter++;
    }
    return counter;
  }

}

var foo = new myFunc('data.json');
document.write(counter); // displays undefined

Update 2

Sorry, thought it would be easier to have a sample code. But here's the real one: https://gist.github.com/BobWassermann/e709ec303477a015b609

I think you have a couple issues here.

First, you're setting your counter to 0 just before you write. It will always be 0 no matter what you do, even with hoisting.

Second, you never call the foo function, so your counter is never incremented.

Third, param.foo isn't public. I think you want it to be this.foo = function(){ ... } .

Here's a simplified version of the code you posted with my tweaks:

var counter = 0;
var foo;

function myFunc() {
  this.foo = function() {
    counter = 1000;
  }
}

foo = new myFunc();
foo.foo();
document.write(counter);

JSFiddle: http://jsfiddle.net/dgrundel/2ojw2332/2/ Note that JSFiddle doesn't allow document.write , so replaced that part.

 function myFunc(param) { this.param = param; this.foo = function () { var object = window.JSON.parse(this.param), counter = 0, i; for (i in object) { counter++; } return counter; }; } var foo = new myFunc('{"a":99}'); out(foo.foo()); function out(s) { document.getElementById('out').innerHTML = '<pre>' + s + '</pre>'; } 
 <div id="out"></div> 

As @Nina Scholz pointed out earlier, I'm retrieving the data asynchron. Javascript started painting the dom before all the values where loaded.

This fixed my problem:

if (document.readyState) {
  setTimeout(function() {
    var objLen = Object.keys(obj).length;
    console.log(objLen);
  }, 100);
}

I'm waiting for the document to be ready, then add an additional timeout as buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM