Royi Namir
Royi Namir

Reputation: 148694

Why exectuing function doesnt work?

I have an input which when im clicking - i want to see alert with '1,2,3,4...' (each press)

<input type='button' value='press' onclick='Clicked();'  />

 <script>
  var t
    function Clicked()
      {
        t=func;
        t();
      }  


     function func()
      {
        var count=0;
         return new  function ()   // <===  new or not new ???
          {
          count++;
          alert(count);
          }
      }
 </script>      

If im adding the 'new' in the return and click , it says : '1,1,1,1,...'

If im removing the 'new' it doesnt work...

My goal is to use this to get : '1,2,3,4...'

Can someone explain to me what happens ?

Upvotes: 0

Views: 89

Answers (5)

Joe
Joe

Reputation: 82634

You need to use the returned function:

var t = func()
function Clicked() {
    t();
}  

function func() {
    var count=0;
    return function () {
        count++;
        alert(count);
    }
}

Example

Upvotes: 2

Riz
Riz

Reputation: 10246

var t
function Clicked()
{
    t=func;
    t();
    }  

var count=0;
function func()
{

    return new  function ()   // <===  new or not new ???
    {
        count++;
        alert(count);
    }
}

Upvotes: 1

locrizak
locrizak

Reputation: 12279

You are getting 1,1,1,1 because you are redefining count every time you call func().

In your case you will need to either put the count variable in the global scope:

var t; var count = 0;

or change the way you are doing things a little:


var t = 0;
function Clicked(){
    t = func(t);
}  


function func(count){
    count++;
    alert(count)
    return count;
}

Personally I like the second one. You have less global variables, one less function declaration, and it is cleaner

Upvotes: 1

Rob
Rob

Reputation: 4947

You're creating a new var count every time the clickevent fires.. You should place the var count = 0 outside the function as a global variable..

oh and btw, throw out the return stuff please this will work properly:

var count = 0;
function func()
{
    count++;
    alert(count);
}

And call this method like this: func();

Upvotes: 1

styrr
styrr

Reputation: 829

You have to put the count declaration out of the "func" function and into the global namespace. Like this:

var count=0;
function func() {
    count++;
    alert(count);
}

Upvotes: 1

Related Questions