1 实例对象与函数对象
- 实例对象:new 函数产生的对象,称为实例对象,简称为对象。
- 函数对象:将函数作为对象使用时,简称为函数对。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>01_准备_函数对象与实例对象</title>
</head>
<body>
<script>
function Fn(){
}
const fn = new Fn();
console.log(Fn.prototype);
Fn.bind({});
Fn.call({});
$('#test');
$.get('/test');
function Person(params){
}
</script>
</body>
</html>
2 回调函数的分类
2.1 同步回调
- 理解:立即执行,完全执行完了才结束,不会放入回调队列中。
- 例子:数组遍历相关的回调函数 / Promise 的 excutor 函数。
2.2 异步回调
- 理解:不会立即执行,会放入回调队列中将来执行。
- 例子:定时器回调 / ajax 回调 / Promise 的成功|失败的回调。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>02_准备_回调函数的分类</title>
</head>
<body>
<script>
const arr = [1, 3, 5];
arr.forEach(item => {
console.log(item);
});
console.log('forEach()之后');
setTimeout(() => {
console.log('timeout callback()');
}, 0);
console.log('setTimeout()之后');
</script>
</body>
</html>
3 JS的error处理
3.1 错误类型
- Error:所有错误的父类型。
- ReferenceError:引用的变量不存在。
- TypeError:数据类型不正确的错误。
- RangeError:数据值不在其所允许的范围内。
- SyntaxError:语法错误。
3.2 错误处理
- 捕获错误:try … catch。
- 抛出错误:throw error。
3.3 error对象的结构
- message 属性:错误相关信息。
- stack 属性:函数调用栈记录信息。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JS的error处理</title>
</head>
<body>
<script>
console.log(a);
console.log('------');
let b = null;
console.log(b.xxx);
let b = {};
b.xxx()
function fn(){
fn();
}
fn();
const c = """";
try {
let d;
console.log(d.xxx);
} catch (error) {
console.log(error.message);
console.log(error.stack);
}
console.log('出错之后');
function something(){
if(Date.now() % 2 === 1){
console.log('当前时间为奇数,可以执行任务');
}else{
throw new Error('当前时间为偶数,无法执行任务');
}
}
try {
something();
} catch (error) {
alert(error.message);
}
</script>
</body>
</html>