在自定义工具函数中,遇到js中的call的一个问题

hellostarfish 2017-01-17 11:20:08
下面代码中的$.formatDate.patternValue[matched[0]].call(this,date)这一句call应该怎么理解啊?

(function($){
$.formatDate=function(date,pattern){
var result=[];
while(pattern.length>0){
$.formatDate.patternParts.lastIndex=0;
var matched=$.formatDate.patternParts.exec(pattern);
if(matched){
console.log(this);
console.log(matched[0]);
console.log($.formatDate.patternValue[matched[0]]);
result.push(
$.formatDate.patternValue[matched[0]].call(this,date)
);
pattern=pattern.slice(matched[0].length);
}else{
result.push(pattern.charAt(0));
pattern=pattern.slice(1);
}

}
return result.join('/');
};

$.formatDate.patternParts=/^(yy(yy)?|M(M(M(M)?)?)?|d(d)?|EEE(E)?|a|H(H)?|h(h)?|m(m)?|s(s)?|S)/;
$.formatDate.monthNames=['January','February','March','April','May','June','July',
'August','September','October','November','December'];
$.formatDate.dayNames=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday', 'Saturday'];

$.formatDate.patternValue={
yy:function(date){
return $.toFixedWidth(date.getFullYear(),2);
},
yyyy:function(date){
return date.getFullYear().toString();
},
MMMM:function(date){
return $.formatDate.monthNames[date.getMonth()];
},
MMM:function(date){
return $.formatDate.monthNames[date.getMonth()].substr(0,3);
},
MM:function(date){
return $.toFixedWidth(date.getMonth()+1,2);
},
M:function(date){
return date.getMonth()+1;
},
dd:function(date){
return $.toFixedWidth(date.getDate(),2);
},
d:function(date){
return date.getDate();
},
EEEE:function(date){
return $.formatDate.dayNames[date.getDay()];
},
EEE:function(date){
return $.formatDate.dayNames[date.getDay()].substr(0,3);
},
HH:function(date){
return $.toFixedWidth(date.getHours(),2);
},
H:function(date){
return date.getHours();
},
hh:function(date){
var hours=date.getHours();
return $.toFixedWidth(hours>12?hours-12:hours,2);
},
h:function(date){
return date.getHours()%12;
},
mm:function(date){
return $.toFixedWidth(date.getMinutes(),2);
},
m:function(date){
return date.getMinutes();
},
ss:function(date){
return $.toFixedWidth(date.getSeconds(),2);
},
s:function(date){
return date.getSeconds();
},
S:function(date){
return $.toFixedWidth(date.getMilliseconds(),3);
},
a:function(date){
return date.getHours()<12?'AM':'PM';
}


}

})(jQuery);




...全文
191 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jshulym 2017-01-20
  • 打赏
  • 举报
回复
你这自定义工具函数怕是只能在对象的方法中通对象冒充的方式才能调用哦
天际的海浪 2017-01-18
  • 打赏
  • 举报
回复
$.formatDate.patternValue[matched[0]]的值是一个函数 .call(this,date)是调用这个函数,并用当前对象的this代替这个函数内的this
  • 打赏
  • 举报
回复
补充:且将data 当做第一个参数传入函数

87,993

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧