【JS深入学习】——函数创建和重载

今天做一个关注/取消的功能,由于需要向后台发送请求,想通过控制用户点击发送的频次减少不必要的请求,即在一定时间内,用户点击多次但只发送一次数据,自然而然想到了使用【函数节流】。

function throttle2(method, context) {
clearTimeout(method.tId);
method.tId = setTimeout(function(){
method.call(context);
}, 1000);
}
但在实际应用中,并不能达到想要效果--每次点击都会发送一次数据,如下:
$(".daili_act_lia").click(function () {
var checkbox = $("#s11"),
options = {},
isFocus = '',
id = $(this).attr("data-id");

function throttle2(method, context) {
clearTimeout(method.tId);
method.tId = setTimeout(function(){
method.call(context);
}, 1000);
}

function myAjax() {
if(checkbox.prop("checked")) {
isFoucs = -1;
}else {
isFoucs = '';
}
options = {
focusId: id,
tag: 2,
focus: isFocus
};
console.log(options)
function returnDate(json) {
console.log(json)
}
Utils.getAjax("POST", CONFIG.API.editFocus, options, returnDate);
}
throttle2(myAjax,this)
});
一直不明白为什么。。。

最后把throttle函数修改为以下就成功了:
function throttle2(method, context) {
clearTimeout(context.tId);
context.tId = setTimeout(function(){
method.call(context);
}, 1000);
}
仔细分析,原来是每次 click 的时候,都重新创建了函数 ‘method’(本例中的 myAjax 函数),那么throttle在内部永远保存着一个定时器不会被清除。才会出现每次点击都会执行method的现象。

结论:
1、 创建函数的方式
  1.1 function fn(){} 函数声明
  1.2 var fn = function(){} 函数表达式
2、 函数名是一个指向函数对象的指针,每创建一个函数,都会在内存重新分配一个地址,即使拥有相同的函数名,他们也不是同一个函数。
3、 JavaScript 中,没有函数重载。
 
原文地址:https://www.cnblogs.com/fayin/p/6229319.html