如何在函数对象文字中传递参数

时间:2017-08-18 18:28:24

标签: javascript jquery

我想将整数作为min和max参数传递给函数,以返回一个随机数,以便在另一个函数中使用。我是Javascript的新手,我正在使用对象文字模式。目前我收到错误“this.randomGenerator不是函数”。如何从randomGenerator返回要在interaction中使用的数字?

bindEvents: function() {
    $('#left').on("click", this.interaction);
},
interaction: function() {
   var selector = this.randomGenerator(0, 3);
   var $columns = $('#left').find('div[col]');

   $columns.children().removeClass('show');
   $columns.eq(selector).children().addClass('show');
},
randomGenerator: function(min, max) {
    var last,      
        value,     
        count = 0, 
        getR = function () { return Math.floor(Math.random() * (max - min)) + min; };

    return function () {
        var random;
        if (count && value !== last) {
           --count;
            return last = value;
        }
        random = getR();
        while (random === last) {
             value = random;
             ++count;
            random = getR();
        }
        return last = random;
    };
},

1 个答案:

答案 0 :(得分:1)

问题是因为this处理程序中的click引用了被点击的元素,而不是包含randomGenerator()函数的对象。

要解决此问题,您可以在使用this(或$.proxy())将其设置为bind()的范围之前,在变量中保留对randomGenerator()的引用功能应该运行。试试这个:

var obj = {
  bindEvents: function() {
    var _this = this;
    $('#left').on("click", $.proxy(_this.interaction, _this));

    // Note you can also use the native bind() method, if preferred:
    // $('#left').on("click", _this.interaction.bind(_this));
  },
  interaction: function() {
    var selector = this.randomGenerator(0, 3);
    console.log(selector()); // just for testing...
    
    var $columns = $('#left').find('div[col]');

    $columns.children().removeClass('show');
    $columns.eq(selector).children().addClass('show');
  },
  randomGenerator: function(min, max) {
    var last,
      value,
      count = 0,
      getR = function() {
        return Math.floor(Math.random() * (max - min)) + min;
      };

    return function() {
      var random;
      if (count && value !== last) {
        --count;
        return last = value;
      }
      random = getR();
      while (random === last) {
        value = random;
        ++count;
        random = getR();
      }
      return last = random;
    };
  }
}

obj.bindEvents();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left">Click me</div>