开发者

Create JavaScript array of function pointer, without calling it

开发者 https://www.devze.com 2022-12-27 09:42 出处:网络
I have the code below. I would like to have an array (buttons) with a single element pointing to the a function (closeFlag).

I have the code below. I would like to have an array (buttons) with a single element pointing to the a function (closeFlag).

<script type="text/javascript">
    var closeFlag = new function() {
        alert('Clicked');
    }
    var buttons = {
        'OK': closeFlag
    }
</script>

However, when loading the page the alert immediately pops up. When the array is constructed, instead of usin开发者_StackOverflow中文版g it as a pointer, JavaScript calls my function. Why? What mistake, misconception do I have?


The new keyword, you will not need it.

<script type="text/javascript">
  var closeFlag = function() {
    alert('Clicked');
  }
  var buttons = {
    'OK': closeFlag
  }
</script>

What's happening in your code is that it's constructing the anonymous function then assigning the result of it (this) to closeFlag.

0

精彩评论

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

关注公众号