函数对象与实例对象
实例对象
new 函数产生的对象,称为实例对象,简称对象
函数对象
将函数作为对象使用,简称为函数对象👇
(函数其实就是一个对象,但只有当把函数作为对象使用时,才能体现它时函数对象,比如下面的.prototype就能体现Fn是个函数对象)
比如说
function Fn(){} // Fn函数
const fn = new Fn(); // Fn()是构造函数,fn是实例对象(简称为对象)
console.log(Fn.prototype);
Fn.bind({}); // Fn()是对象
括号
()的左边是函数,点.的左边是对象
回调函数
满足三个条件才能称为回调函数
- 自己定义的函数
- 自己没有亲自调用
- 但最终执行了
回调函数主要分为两种👇
同步回调
立即执行,完全执行了才结束,不会放入回调队列中
异步回调
不会立即执行,会放入回调队列中将来执行
⚠️ 要判断是同步回调还是异步回调,可以在回调函数后面加一个console.log()(或者别的东西),如果这个console.log()后于回调函数执行了,那么这个回调函数就是同步的,否则是异步的
// 同步回调
const arr = [1, 2, 3];
// 这里括号中包的 item => {} 就是回调函数
arr.forEach(item => {
console.log(item, "item");
})
console.log("forEach()执行之后打印");
console.log("-----------");
// 异步回调
setTimeout(() => {
console.log("timeout callback");
}, 0);
console.log("setTimeOut()执行之前打印");
常见的内置error
promise中有成功回调和失败回调,这个就与error有关系了,下面来看一下
JS的error处理
error 类型
- Error:所有错误的父亲类
-
ReferenceError: 引用错误,引用的变量不存在
-
TypeError: 数据类型不正确
-
RangeError:数据值不在其所允许的范围内
-
SyntaxError :语法错误
-
// ReferenceError
console.log(a); // Uncaught ReferenceError: a is not defined
console.log("----"); // 没有捕获error,下面的代码不执行
// TypeError
let b = null;
console.log(b.xxx); // Uncaught TypeError: Cannot read property 'xxx' of null
b.xxx; // Uncaught TypeError: Cannot read property 'xxx' of null
let b = {};
b.xxx(); // Uncaught TypeError: b.xxx is not a function
// RangeError
// 函数内部调用自己会有一个次数的限制,超出了之后会报RangeError
function fn(){ // 函数递归调用
fn()
}
fn(); // Uncaught RangeError: Maximum call stack size exceeded
// SyntaxError
const c = """"; // Uncaught SyntaxError: Unexpected string
// 正常应该是这样写 const c = "''";
error 处理
- 捕获错误 try…catch
try {
let a;
console.log(a.xxx);
} catch (error) {
console.log(error);
console.log(error.message,"error.message");
console.log(error.stack,"error.stack");
}
- 抛出错误 throw error
try…catch中的错误是系统检测出来的错误,throw error是自己可以主动抛出的错误
function some(){
if(Date.now % 2 === 1){
console.log("当前时间为奇数,可以执行");
}else{
throw new Error("当前时间为偶数,不能执行");
}
}
try {
some();
} catch (error) {
console.log(error.message);
}
error 对象
error 对象中默认有两个属性,一个message,一个stack。其中:
- message:错误相关信息,提示文本
- stack:函数调用栈记录信息,带有相关信息的提示文本
Promise[翻译:承诺,许诺]
What Promise
-
抽象表达
Promise是JS中进行
异步编程的新的解决方案旧的解决方案是纯回调形式(纯回调的纯的意思是只有回调没有promise,因为promise中也有回调)
普通函数是函数去做什么,构造函数是它的实例去做什么
- 具体表达
- 语法上来说:promise是一个构造函数(构造函数主要是用来新建实例对象,也就是它的实例去干什么)
- 功能上来说:promise对象用来封装一个异步操作并获取其结果
Promise 状态改变
Promise 有三种状态:
- pending:初始状态
- resolved:成功
- rejected:失败
Promise状态的改变只有两种:
- pending变为resolved
- pending变为rejected
一个Promise对象只能改变一次,无论是成功还是失败,都会有一个结果数据;成功的结果数据一般称为value,失败的结果数据一般称为reason
Promise基本流程
Promise基本使用
// 1.创建一个新的Promise对象
const p = new Promise((resolve, reject) => {
// 这里的resolve和reject都是函数类型
// 2.执行异步操作任务
setTimeout(() => {
const time = Date.now();
if (time % 2 === 0) {
// 3.1 成功则调用resolve(value)
resolve("成功了,time:" + time);
} else {
// 3.2 失败则调用reject(reason)
reject("失败了,time:" + time);
}
}, 1000);
})
p.then(
value => { // 接收得到成功的value值 onResolved
console.log("成功的回调:", value);
},
reason => { // 接收得到失败的reason值 onRejected
console.log("失败的回调:", reason);
}
)
为什么用Promise
执行器函数是同步回调
-
指定回调函数的方式更灵活
具体怎么说呢?
- 纯回调函数:必须在启动异步任务前指定
- promise:启动异步任务 =》 返回promise对象 =》 给promise对象绑定回调函数(甚至可以在异步任务结束后指定也能得到结果数据)
// 1.创建一个新的Promise对象
const p = new Promise((resolve, reject) => {
// 这里的resolve和reject都是函数类型
// 2.执行异步操作任务
setTimeout(() => {
const time = Date.now();
if (time % 2 === 0) {
// 3.1 成功则调用resolve(value)
resolve("成功了,time:" + time);
} else {
// 3.2 失败则调用reject(reason)
reject("失败了,time:" + time);
}
}, 1000);
})
setTimeout(() => {
p.then(
value => { // 接收得到成功的value值 onResolved
console.log("成功的回调:", value);
},
reason => { // 接收得到失败的reason值 onRejected
console.log("失败的回调:", reason);
}
)
}, 2000);
// 这里的2000ms可以看出指定回调函数是在成功/失败以后才指定的,因为前面的成功或失败只需要1秒钟
- 支持链式调用,可以解决回调地狱问题
回调地狱问题:回调函数嵌套调用,外部回调函数异步执行的结果是嵌套的回调函数执行的条件
回调地狱的缺点:不便于阅读,不便于异常处理。
// 回调地狱问题
// 下面这三个函数串联执行(上一个执行完执行下一个)
doSome(function (result) {
doSomesecond(result, function (newResult) {
doSomeThird(newResult, function (finalResult) {
console.log('final result', finalResult);
}, failureCallback)
}, failureCallback)
}, failureCallback)
// 使用Promise的链式调用解决回调地狱
// 这个不是最好的解决方法,因为执行的过程中还是有回调函数。。
doSome().then(function (result) {
return doSomeSecond(retult);
}).then(function (newResult) {
return doSomeThird(newResult);
}).then(function (finalResult){
console.log('final result', finalResult);
}).catch(failureCallback);
// 上面三个函数doSome/doSomeSecond/doSomeThird中任何一个出现异常都会传到catch(failureCallback)
// error能传递过来的这个处理叫做 异常传透
// async/await 终极解决回调地狱方法
async function request(){
try {
const result = await doSome();
const newResult = await doSomeSecond();
const finalResult = await doSomeThird();
console.log('final result', finalResult);
} catch (error) {
failureCallback(error);
}
}
promise API
-
promise 构造函数:
promise(excutor){}- excutor函数:同步执行
(resolver, reject) => {} - resolver函数:函数内部定义成功时调用的函数
value => {} - reject函数:函数内部定义失败时调用的函数
reason => {}
说明:excutor会在promise内部立即同步回调,异步操作代码在执行器中执行
- excutor函数:同步执行
-
Promise.prototype.then()方法:
(onResolved, onRejected) => {}- onResolved函数:成功的回调函数
(value) => {} - onRejected函数:失败的回调函数
(reason) => {}
说明:指定用于得到成功 value 的成功回调和用于得到失败 reason 的失败回调,返回一个新的promise对象
- onResolved函数:成功的回调函数
-
Promise.prototype.catch()方法:
(onRejected) => {}- onRejected函数:失败的回调函数
(reason) => {}
说明:then()的语法糖,相当于:
then(undefined, onRejected) - onRejected函数:失败的回调函数
-
Promise.resolve()方法:
(value) => {}- value:成功的数据或promise对象
说明:返回一个成功/失败的promise对象
-
Promise.reject()方法:
(reason) => {}- reason:失败的数据或promise对象
说明:返回一个成功/失败的promise对象
-
Promise.all()方法:
(promises) => {}- promises:包含n个promises的数组
说明:返回一个新的promise,只有所有的promise都成功才成功,有一个失败了就直接失败
-
Promise.race()方法:
(promises) => {}- promises:包含n个promises的数组
说明:返回一个新的promise,第一个完成的promise的结果状态就是最终的结果状态
函数对象与实例对象详解
158

被折叠的 条评论
为什么被折叠?



