JavaScript进阶:js的一些学习笔记-this指向,call,apply,bind,防抖,节流

文章目录

        • [1. this指向](#1. this指向)
          • [1. 箭头函数 this的指向](#1. 箭头函数 this的指向)
        • [2. 改变this的指向](#2. 改变this的指向)
          • [1. call()](#1. call())
          • [2. apply()](#2. apply())
          • [3. bind()](#3. bind())
        • [3. 防抖和节流](#3. 防抖和节流)
          • [1. 防抖](#1. 防抖)
          • [2. 节流](#2. 节流)
1. this指向
1. 箭头函数 this的指向
  • 箭头函数默认帮我们绑定外层this的值,所以在箭头函数中this的值和外层的this是一样的
  • 箭头函数中的this引用的就是最近作用域中的this
  • 向外层作用域下,一层一层查找this,知道有this的定义

注意:

  1. 事件回调函数使用箭头函数时,this为全局的window,因此dom事件回调函数如果里面需要用到dom对象的this,不推荐使用箭头函数

    js 复制代码
    const btn = document.querySelector('button');
    
    /*btn.addEventListener('click',function(){
    		console.log(this);
    		// this指向btn
    	})*/
    
    btn.addEventListener('click',()=>{
        console.log(this);
        // this 指向window
    })
  2. 基于原型的面向对象也不推荐采用箭头函数

    js 复制代码
    function Person(){}
    Person.prototype.play = function(){
        console.log(this);
        // this 指向Person
    }
    
    Person.prototype.walk = ()=>{
        console.log(this);
        // this 指向window
    }
    
    
    const p1 = new Person();
    p1.play();
    p1.walk();
2. 改变this的指向
1. call()

使用call方法调用函数,同时指定被调用函数中this的值

js 复制代码
function fn(x,y){
    console.log(this);
    // 指向window
    console.log(x,y);
}
fn();

const obj = {
    name:'liuze'
}

fn.call(obj,1,2);
// 此时fn里边的this指向obj,1,2相当于实参
2. apply()

fun.apply(thisArg,argsArray)

  • thisArg:在fun函数运行时指定的this值

  • argsArray:传递的值,必须包含在数组里面

  • 返回值就是函数的返回值

js 复制代码
function fn(x,y){
    console.log(this);
    // 指向window
    console.log(x,y);
    return x+y;
}
fn();

const obj = {
    name:'liuze'
}

const res = fn.apply(obj,[1,2]);
// 此时fn函数中的this指向obj
console.log(res);
// 3
3. bind()

不会调用函数,但是能改变函数内部this的指向

fun.bind(thisArg,arg1,arg2,...)

  • thisArg:在fun函数运行时指定this的值
  • arg1,arg2:传递的其他参数
  • 返回由指定的this值和初始化参数改造的原函数拷贝(新函数)
  • 如果只是想改变this指向,并且不香调用这个函数的时候,可以使用bind
js 复制代码
function fn(x,y){
    console.log(this);
    // 指向window
    console.log(x,y);
    return x+y;
}
fn();

const obj = {
    name:'liuze'
}

const fun2 = fn.bind(obj,1,2);
// 此时fn函数中的this指向obj
console.log(fun2());
3. 防抖和节流
1. 防抖

单位时间内,频繁触发事件,只执行最后一次

使用场景

搜索框搜索输入,只需用户最后一次输入完,再发送请求。

利用防抖来处理-鼠标划过盒子显示文字

html 复制代码
<!DOCTYPE html>
<html>
<head>
	<title>javascript</title>
	<style type="text/css">
		*{
			margin: 0;
			padding: 0;
		}
		.box{
			width: 200px;
			height: 200px;
			background-color: red;
			margin: 0 auto;
			line-height: 200px;
			text-align: center;
		}
	</style>
</head>
<body>
	<div class="box">1</div>
</body>
	<script type="text/javascript">
		const box = document.querySelector('.box');
		var i = 1;
		box.addEventListener('mousemove',function(){
			box.innerHTML = i ++;
		})
		
	</script>
</html>

运行结果:

实现方式:

  1. lodash提供的防抖来处理

    js 复制代码
    const box = document.querySelector('.box');
    var i = 1;
    function mouseMove(){
        box.innerHTML = i ++;
    }
    box.addEventListener('mousemove',_.debounce(mouseMove,500))
    // 1. 利用lodash库实现防抖,500ms之后采取+1
  2. 手写一个防抖函数来处理

    js 复制代码
    const box = document.querySelector('.box');
    var i = 1;
    var timer = null;
    box.addEventListener('mousemove',function(){
        if(timer != null){
            clearTimeout(timer);
        }
        timer = setTimeout(()=>{
            box.innerHTML = i++;
        },500);
        // 休眠500ms
    })	

运行结果:

2. 节流

单位时间内,频繁触发事件,只执行一次

实现方式:

  1. 利用lodash提供的节流来实现

    js 复制代码
    const box = document.querySelector('.box');
    var i = 1;
    function mouseMove(){
        box.innerHTML = i++;
    }
    box.addEventListener('mousemove',_.throttle(mouseMove,3000));
  2. 手写一个防抖函数来处理

    js 复制代码
    const box = document.querySelector('.box');
    var i = 1;
    var timer = null;	
    box.addEventListener('mousemove',function(){
        if(!timer){
            timer = setTimeout(function(){
                box.innerHTML = i++;
                timer = null;
            },3000);
        }
    });

运行结果:

相关推荐
千寻xun3 小时前
一、理论篇-NVME协议学习笔记
笔记·学习·fpga开发·nvme ssd·nvme协议
researcher-Jiang4 小时前
高性能计算之OpenMP——超算习堂学习1
android·java·学习
随风一样自由4 小时前
【前端独角兽】刚进入前端领域的前端开发用jQuery还是Vue3?
前端·javascript·vue3·jquery
YHHLAI5 小时前
[特殊字符] 面试中的 Promise —— 从入门到精通
前端·javascript·面试
weixin_BYSJ19876 小时前
SpringBoot + MySQL 乒乓球运动员信息管理系统项目实战--附源码04954
java·javascript·spring boot·python·django·flask·php
沪飘大军6 小时前
ll-llm:一个零依赖、可插拔的 OpenAI 兼容 LLM 代理
javascript
山河木马8 小时前
GPU自动处理专题3-NDC怎么映射成屏幕像素坐标(视口变换)
javascript·webgl·图形学
MartinYeung58 小时前
[论文学习]大语言模型安全综述:攻击、防御、对齐、度量与护栏的深度解析
学习·安全·语言模型
Piko6148 小时前
锐捷 VSU 虚拟化堆叠配置
运维·网络·笔记
AOwhisky9 小时前
Python 学习笔记(第三期)——流程控制:条件判断与循环结构
运维·笔记·python·学习·云原生·流程控制·循环