I'm passing jQuery UI format date function as parameter somewhere in my code.
However it's failing with error Cannot read property 'dayNamesShort' of undefined
.
To reproduces :
jQuery.datepicker.formatDate( "yy-mm-dd", new Date()); // works
var formatDate = jQuery.datepicker.formatDate;
formatDate( "yy-mm-dd", new Date() ); // does not works
I'm guessing this is due to some use of this
within the jQuery method, but I don't know how to fix.
Here's a complete reproductible snippet:
(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] thanks to @T.J Crowder comments and answers in the duplicate question, here's a set of possible answers :
(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>