系列文章目录
文章目录
一、实例对象和函数对象
1. 函数对象
将函数作为对象使用时,简称为函数对象。
2. 实例对象
new 构造函数或类产生的对象,称之为实例对象。
3. 举例
// 函数对象
function Person(name, age){
this.name = name
this.age = age
}
Person.a = 1 // 将Person看成一个对象
const p1 = new Person('小宏', 22) //p1是Person的实例对象
console.log(p1)
二、回调函数的分类
1. 什么是回调?
我们定义的,我们没有调用,最终执行了
2. 同步回调函数
- 理解:立即在主线程上回调,不会放入回调队列中。
- 例子:数组遍历相关的回调函数 / Promise的executor函数
let arr = [1, 3, 5, 7, 9]
arr.forEach((item)=>{
console.log(item);
})
console.log('主线程的代码');
同步的回调:按顺序执行
3. 异步回调函数
- 理解:不会立即执行,会放入回调队列中以后执行
- 例子:定时器回调 / ajax回调 / Promise的成功、失败的回调
setTimeout(()=>{
console.log('@');
}, 1000)
console.log('主线程的代码');
同步的回调:按队列执行
三、JS 中的 Error
1. 错误类型
Error:所有错误的父类型
- ReferenceError:引用的变量不存在
console.log(a);
没有定义,直接输出
- TypeError:数据类型不正确
const demo = () => {
}
demo()()
demo() 为undefined,undefined() 为类型错误
- RangeError:数据值不在其所允许的范围内——死循环
const demo = () => {
demo()}
demo()
死循环,队列栈已满
- SyntaxError:语法错误
console.log(1;
语法错误,丢失了半个括号
2. 捕获错误
捕获错误:使用
try{} catch{}
try {
console.log(1);
console.log(a);
console.log(2);
} catch (error) {
console.log('代码执行错误,错误原因:', error);
}
使用异常捕获,错误不飘红
3. 抛出错误
抛出错误:
throw error
function demo() {
const date = Date.now()
if (date % 2 === 0) {
console.log('偶数,可以正常工作');
} else {
throw new Error('奇数,不可以工作')
}
}
try {
demo()
} catch (error) {
console.log('@', error);
}
获取时间戳,偶数可工作,奇数不可工作
不积跬步无以至千里 不积小流无以成江海
点个关注不迷路,持续更新中…