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

json - Create JavaScript array of function pointer, without calling it - Stack Overflow

programmeradmin2浏览0评论

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 using it as a pointer, JavaScript calls my function. Why? What mistake, misconception do I have?

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 using it as a pointer, JavaScript calls my function. Why? What mistake, misconception do I have?

Share Improve this question asked Apr 16, 2010 at 22:42 sibidibasibidiba 6,3708 gold badges42 silver badges50 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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)

  1. 暂无评论