持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第17天,点击查看活动详情
深浅拷贝
-
首先浅拷贝和深拷贝只针对想Object,Array这样的复杂对象,简单来说,浅拷贝只复制一层对象的属性,二深拷贝则复制了所有的层级。
-
对于字符串类型,浅复制是对值的复制,对于对象来说,浅复制是对对象地址的复制,并没 有开辟新的栈,也就是复制的结果是两个对象指向同一个地址,修改其中一个对象的属性,则另一个对象的属性也会 改变,而深复制则是开辟新的栈,两个对象对应两个不同的地址,修改一个对象的属性,不会改变另一个对象的属性。
const obj = { uname: 'pink', age: 18, hobby: ['乒乓球', '足球'], family: { baby: '小pink' } } // 把对象转换为 JSON 字符串 // console.log(JSON.stringify(obj)) const o = JSON.parse(JSON.stringify(obj)) console.log(o) o.family.baby = '123' console.log(obj)
异常处理
了解 JavaScript 中程序异常处理的方法,提升代码运行的健壮性。
throw
异常处理是指预估代码执行过程中可能发生的错误,然后最大程度的避免错误的发生导致整个程序无法继续运行。
<script>
function counter(x, y) {
if(!x || !y) {
// throw '参数不能为空!';
throw new Error('参数不能为空!')
}
return x + y
}
counter()
</script>
总结:
throw抛出异常信息,程序也会终止执行throw后面跟的是错误提示信息Error对象配合throw使用,能够设置更详细的错误信息
try ... catch
<script>
function foo() {
try {
// 查找 DOM 节点
const p = document.querySelector('.p')
p.style.color = 'red'
} catch (error) {
// try 代码段中执行有错误时,会执行 catch 代码段
// 查看错误信息
console.log(error.message)
// 终止代码继续执行
return
}
finally {
alert('执行')
}
console.log('如果出现错误,我的语句不会执行')
}
foo()
</script>
总结:
try...catch用于捕获错误信息- 将预估可能发生错误的代码写在
try代码段中 - 如果
try代码段中出现错误后,会执行catch代码段,并截获到错误信息
this
了解函数中 this 在不同场景下的默认值,知道动态指定函数 this 值的方法。
默认值
this 是 JavaScript 最具“魅惑”的知识点,不同的应用场合 this 的取值可能会有意想不到的结果,在此我们对以往学习过的关于【 this 默认的取值】情况进行归纳和总结。
普通函数
普通函数的调用方式决定了 this 的值,即【谁调用 this 的值指向谁】,如下代码所示:
<script>
// 普通函数
function sayHi() {
console.log(this)
}
// 函数表达式
const sayHello = function () {
console.log(this)
}
// 函数的调用方式决定了 this 的值
sayHi() // window
window.sayHi()
// 普通对象
const user = {
name: '小明',
walk: function () {
console.log(this)
}
}
// 动态为 user 添加方法
user.sayHi = sayHi
uesr.sayHello = sayHello
// 函数调用方式,决定了 this 的值
user.sayHi()
user.sayHello()
</script>
注: 普通函数没有明确调用者时 this 值为 window,严格模式下没有调用者时 this 的值为 undefined。
箭头函数
箭头函数中的 this 与普通函数完全不同,也不受调用方式的影响,事实上箭头函数中并不存在 this !箭头函数中访问的 this 不过是箭头函数所在作用域的 this 变量。
<script>
console.log(this) // 此处为 window
// 箭头函数
const sayHi = function() {
console.log(this) // 该箭头函数中的 this 为函数声明环境中 this 一致
}
// 普通对象
const user = {
name: '小明',
// 该箭头函数中的 this 为函数声明环境中 this 一致
walk: () => {
console.log(this)
},
sleep: function () {
let str = 'hello'
console.log(this)
let fn = () => {
console.log(str)
console.log(this) // 该箭头函数中的 this 与 sleep 中的 this 一致
}
// 调用箭头函数
fn();
}
}
// 动态添加方法
user.sayHi = sayHi
// 函数调用
user.sayHi()
user.sleep()
user.walk()
</script>
在开发中【使用箭头函数前需要考虑函数中 this 的值】,事件回调函数使用箭头函数时,this 为全局的 window,因此DOM事件回调函数不推荐使用箭头函数,如下代码所示:
<script>
// DOM 节点
const btn = document.querySelector('.btn')
// 箭头函数 此时 this 指向了 window
btn.addEventListener('click', () => {
console.log(this)
})
// 普通函数 此时 this 指向了 DOM 对象
btn.addEventListener('click', function () {
console.log(this)
})
</script>
同样由于箭头函数 this 的原因,基于原型的面向对象也不推荐采用箭头函数,如下代码所示:
<script>
function Person() {
}
// 原型对像上添加了箭头函数
Person.prototype.walk = () => {
console.log('人都要走路...')
console.log(this); // window
}
const p1 = new Person()
p1.walk()
</script>
this指向
以上归纳了普通函数和箭头函数中关于 this 默认值的情形,不仅如此 JavaScript 中还允许指定函数中 this 的指向,有 3 个方法可以动态指定普通函数中 this 的指向:
call
使用 call 方法调用函数,同时指定函数中 this 的值,使用方法如下代码所示:
<script>
// 普通函数
function sayHi() {
console.log(this);
}
let user = {
name: '小明',
age: 18
}
let student = {
name: '小红',
age: 16
}
// 调用函数并指定 this 的值
sayHi.call(user); // this 值为 user
sayHi.call(student); // this 值为 student
// 求和函数
function counter(x, y) {
return x + y;
}
// 调用 counter 函数,并传入参数
let result = counter.call(null, 5, 10);
console.log(result);
</script>
总结:
call方法能够在调用函数的同时指定this的值- 使用
call方法调用函数时,第1个参数为this指定的值 call方法的其余参数会依次自动传入函数做为函数的参数
apply
使用 call 方法调用函数,同时指定函数中 this 的值,使用方法如下代码所示:
<script>
// 普通函数
function sayHi() {
console.log(this)
}
let user = {
name: '小明',
age: 18
}
let student = {
name: '小红',
age: 16
}
// 调用函数并指定 this 的值
sayHi.apply(user) // this 值为 user
sayHi.apply(student) // this 值为 student
// 求和函数
function counter(x, y) {
return x + y
}
// 调用 counter 函数,并传入参数
let result = counter.apply(null, [5, 10])
console.log(result)
</script>
总结:
apply方法能够在调用函数的同时指定this的值- 使用
apply方法调用函数时,第1个参数为this指定的值 apply方法第2个参数为数组,数组的单元值依次自动传入函数做为函数的参数
bind
bind 方法并不会调用函数,而是创建一个指定了 this 值的新函数,使用方法如下代码所示:
<script>
// 普通函数
function sayHi() {
console.log(this)
}
let user = {
name: '小明',
age: 18
}
// 调用 bind 指定 this 的值
let sayHello = sayHi.bind(user);
// 调用使用 bind 创建的新函数
sayHello()
</script>
注:bind 方法创建新的函数,与原函数的唯一的变化是改变了 this 的值。
防抖节流
- 防抖(debounce) 所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间
- 节流(throttle) 所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数
节流封装
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.box {
width: 500px;
height: 500px;
background-color: #ccc;
color: #fff;
text-align: center;
font-size: 100px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box"></div>
<!-- 导入 lodash.min.js -->
<script src="./lodash.min.js"></script>
<script>
// 需求1: 点击box(鼠标移动触发频率更高),就触发修改div内容的逻辑;
let box = document.querySelector('.box');
let i = 0;
function setNum() {
box.innerHTML = ++i;
}
// 1. 普通 - 绑定事件
// box.addEventListener('mousemove', setNum);
// 2. 节流 - 自己封装实现
box.addEventListener('mousemove', throttle(setNum, 3000));
// 封装一个方法 _.throttle(setNum, 3000)
// 通过打印,验证返回值是一个函数
// console.log(_.throttle(setNum, 3000));
// 两个参数: 函数和时间; 一个返回值: 事件对应的函数;
function throttle(fn, time) {
// 上一次的触发时间,最好设置为返回值函数外部的变量, 下一次触发,也要用到上一次的值;
let startTime = 0;
return function () {
// 逻辑 - 节流就是规定时间内触发第一次;
// 如果间隔时间超过规定时间,就可以再次触发;
// 获取当前时间 - 毫秒值
let nowTime = Date.now();
// 判断当前时间和上一次触发的时间差,是否大于传递过来的time
if (nowTime - startTime > time) {
// 如果大于传递过来的time,就要执行fn();
fn();
// 如果本次能够执行,那么上一次的时间就应该更新为本次时间;
startTime = nowTime;
}
}
}
</script>
</body>
</html>
防抖封装
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.box {
width: 500px;
height: 500px;
background-color: #ccc;
color: #fff;
text-align: center;
font-size: 100px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box"></div>
<!-- 导入 lodash.min.js -->
<script src="./lodash.min.js"></script>
<script>
// 需求1: 点击box(鼠标移动触发频率更高),就触发修改div内容的逻辑;
let box = document.querySelector('.box');
let i = 0;
function setNum() {
box.innerHTML = ++i;
}
// 1. 普通 - 绑定事件
// box.addEventListener('mousemove', setNum);
// 2. 防抖 - 自己封装实现
box.addEventListener('mousemove', debounce(setNum, 1000));
// 封装一个方法 _.debounce(setNum, 1000)
// 通过打印,验证返回值是一个函数
// console.log(_.debounce(setNum, 1000));
// 两个参数: 函数和时间; 一个返回值: 事件对应的函数;
function debounce(fn, time) {
// return的外面定义一个变量,赋值为定时器的id值;
let timerID; // 一定要用 let 定义,不能用const
return function () {
// 每次触发都清除上一次的操作;
clearTimeout(timerID);
// 多次触发,规定时间之内,取消掉之前的操作; (延时器)
// 此处的 timerID 前面不能带有 let
timerID = setTimeout(function () {
// 延迟 time 时间,执行 fn();
fn();
}, time);
}
}
</script>
</body>
</html>
最后是原图🌹