一、函数节流
函数节流:控制函数执行的频率,只有满足了条件之后,函数的代码才能够执行
节流:return
原理:return 后面的代码不执行
步骤:
- 声明锁 var lock = true
- 判断锁的状态
- 更改锁的状态
- 重置锁的状态
执行代码:
1 // 声明标识 --- 锁
2 var lock = true;
3 $('button').click(function() {
4 // 判断锁的状态
5 if (!lock) {
6 return;
7 }
8 // 更改锁的状态
9 lock = false;
10
11 $('#box').animate({
12 left: parseInt($('#box').css('left')) + 300 + 'px'
13 }, 1000, function() {
14 // 重置状态
15 lock = true;
16 });
17 });
二 延时器
setTimeout(fn, time)
fn:执行的回调函数
time:延迟执行的时间
执行代码:
1 // 声明标识 --- 锁
2 var lock = true;
3 $('button').click(function() {
4
5 // 判断锁的状态
6 if (!lock) {
7 return;
8 }
9 // 更改锁的状态
10 lock = false;
11 console.log("我被点击了");
12 // 延时器
13 setTimeout(function() {
14 // 更改锁的状态
15 lock = true;
16 }, 1000);
17 });
三, each
两种用法:
第一种:用于遍历对象(dom对象)
$(dom).each(function(index, value) {
index:表示遍历当前对象的索引
value:表示遍历当前对象,和this等价 一般使用this代替value
});
第二种:遍历数组和对象
$.each(target, function(index, value) {
target:要遍历的数组或对象
index:表示遍历当前元素的索引或者对象的键
value:表示遍历当前元素的值或者当前对象的值,和this等价 一般使用this代替value
});
执行代码:
1 $('.box').each(function(index, value) {
2 console.log(index, value, this, arguments);
3 });
4
5 var arr = [0, 1, 3, 4, 6, 777];
6 $.each(arr, function(index, value) {
7 console.log(index, value, this, arguments);
8
9 });
10 var obj = {
11 aa: 11,
12 bb: 22,
13 cc: 33
14 }
15 $.each(obj, function(index, value) {
16 console.log(index, value, this, arguments);
17
18 });
四,this
1.代表当前的对象
2.如果是在循环绑定的事件中,代表触发当前事件的元素对象。
3.如果在遍历的数组,代表当前的元素。
4.无主函数的this指向window(函数自执行)
五· call与apply
call与apply都能改变this的指向
所有的函数天生都可以调用call与apply
区别:
传参方式不同
fn.call(target, arg1,arg2,…) 参数直接写在要改变this指向的target之后
fn.apply(target, [arg1, arg2, …]) 参数使用数组的方式进行传递
call是多个参数,不固定的,apply只需要两个参数。
1. /*
2. 相同:call与apply都能改变this的指向
3. 区别:调用函数的时候,传入参数的方式不同
4. */
5. function demo(a, b) {
6. console.log(this, arguments);
7. console.log(a + b);
8. }
9. demo(1, 2);
10. var obj1 = {
11. name: 'obj1'
12. }
13. var obj2 = {
14. name: 'obj2'
15. }
16. //通过call改变this指向
17. demo.call(obj1, 1, 2);
18. //通过apply改变this指向
19. demo.apply(obj2, [1, 2]);