开发者

Why exectuing function doesnt work?

开发者 https://www.devze.com 2023-04-12 18:08 出处:网络
I have an inputwhich when im clicking - i want to see alert with \'1,2,3,4...\' (each press) <input type=\'button\' value=\'press\' onclick=\'Clicked();\'/>

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 ?


You need to use the returned function:

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

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

Example


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);
}


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();


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


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

var count=0;
function func()
{

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

精彩评论

暂无评论...
验证码 换一张
取 消