将函数作为变量传递会使其失败

时间:2019-02-21 10:39:34

标签: javascript jquery jquery-ui

我正在将jQuery UI格式的日期函数作为参数传递给代码中的某个地方。

但是它失败并显示错误Cannot read property 'dayNamesShort' of undefined

要复制:

jQuery.datepicker.formatDate( "yy-mm-dd", new Date()); // works

var formatDate = jQuery.datepicker.formatDate;
formatDate( "yy-mm-dd", new Date() ); // does not works

我猜这是由于jQuery方法中使用了this,但我不知道如何解决。

这是完整的可复制代码段:

(function($){
  $(function(){
    console.log(jQuery.datepicker.formatDate( "yy-mm-dd", new Date() ));
    
    var formatDate = jQuery.datepicker.formatDate;
    console.log(formatDate( "yy-mm-dd", new Date() ));  

  });  
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

[edit]感谢@ T.J Crowder在重复问题中的评论和答案,这里有一组可能的答案:

(function($){
  $(function(){
    console.log(jQuery.datepicker.formatDate( "yy-mm-dd", new Date() ));
    
    // wrapping in a new function
    var formatDate = function(format, date, options){ 
      return jQuery.datepicker.formatDate(format, date, options);
    };
    console.log("1:", formatDate( "yy-mm-dd", new Date() ));

    // preserving the this context within jquery code
    var formatDate2 = jQuery.datepicker.formatDate.bind(jQuery.datepicker);
   
    console.log("2:",formatDate2( "yy-mm-dd", new Date() ));

    // applying this (less practical though)
    var formatDate3 = jQuery.datepicker.formatDate;
   
    console.log("3:",formatDate3.apply(jQuery.datepicker, [ "yy-mm-dd", new Date() ]));

  });  
})(jQuery);
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

0 个答案:

没有答案