4. 现代 javascript class 专题 和 异步专题
class 专题
定义 class
//es5 类的定义 属性定义在 function 上, 方法定义在原型链上
function foobar(){
this.foo_ = 'foo';
this.bar_ = 'bar';
}
foobar.prototype.sayHello = function(){ console.log('hello') }
const fb = new foobar();
fb.sayHello();
// es6 class 语法
class foobar2{
constructor(){
this.foo_ = 'foo';
this.bar_ = 'bar';
}
sayHello(){ console.log('hello') }
}
const fb2 = new foobar2();
fb2.sayHello();
继承
class father {
sayHi(){ console.log('Hi') }
}
class son extends father{
constructor () {
super();
this.me='son'
}
sayHello(){ console.log('hello') }
}
const son1 = new son();
// 调用 father 类的 sayHi 方法时 找自己的原型 son.prototype 是否含有这个 方法
// 通过查看父类的原型判断 是否调用的父类的方法 其中 son.prototype.__proto__=father.prototype
// 通过 类名.hasOwnProperty('方法的名称') 判断是否含有该方法
son1.sayHi();
异步专题
javascript 中的事件循环 (不限制时间)
物理线程的事件循环是有事件限制的

用事件提交器 将 事件 推入事件 队列 然后 通过事件循环 处理到当前 事件时 然后处理 事件处理函数 (回调函数)
Promise 语法糖 使用
把多重的 函数 嵌套请求 写得更简单
链式调用
eg:多次 发起 fetch 请求
window.fetch('//xx.com/1').then(data=>{
window.fetch('//xx.com/2');
}).then(data=>{
window.fetch('//xx.com/3');
}).then(_=>{
console.log('ok');
})
eg: 异步 多次 发起 延时3s 执行函数
function fn (){
console.log(Date.now())
}
function delay3sPromise( fn ){
return new Promise( (resolve, reject) =>{
// resolve 通知 promise 业务代码 成果 并 返回结果
// reject 函数执行失败 并返回错误
setTimeout(_ => {
try{
const ret = fn();
resolve(ret);
}catch(err){
reject(err); //发生了错误
}
}, 3000)
} )
}
// 调用
delay3sPromise(fn).then(_=>{
return delay3sPromise(fn);
}).then(_=>{
return delay3sPromise(fn);
}).catch(err => {
console.log(err);
})
eg: 同步 请求 处理
function delaySame(fn){
return new Promise(_ => {
try{
return Promise.resolve(data)
}catch(err){
return Promise.reject(err)
}
})
}
//调用
dedelaySame(fn).then(data=>{
console.log(data);
}).catch(err){
console.log(err);
}
要点
Promise 一旦创建是 一定会执行的
创建一个 Promise 只能调用一次
Promise的 三个状态: pending (执行代码前)-> fulfilled(执行成功) | rejected(执行失败)
try/catch 不能捕获 Promise 中的 异常(是使用 Promise 后的 catch 方法进行捕获)
eg: new Promise(fn).catch(err=>{ console.log(err) })
链式调用
三种异步
macro task 宏任务
micro task 微任务 (优先级 比 宏任务高)
物理线程

eg: 同步代码先执行 同步代码后的 异步代码先执行 后执行 异步代码
console.log(0)
setTimeout(_=> console.log(1)) // 异步代码 宏任务
new Promise((resolve, reject)=>{ // 该回调为 同步执行
console.log(2)
resolve()
console.log(3)
}).then(_=>{ // 异步代码 微任务
console.log(4)
}).then(_=>{ // 异步代码 微任务
console.log(5)
})
console.log(6)
结果: 0 2 3 6 4 5 1
async 和 await 用法
一种比 Promise 更好用的语法
Promise 语法
eg:
function copyFile(src, dst) {
return readFile(src).then(content => {
return writeFile(dst, content)
})}
copyFile('src', 'dst')
.then(_ => console.log('finished'))
.catch(err => console.error(err))
async 和 await 语法
1. async 函数 只有在 async 函数内使用
2. wait 是 .then 的 语法糖
3. async await 函数内 能使用 try catch
async function copyFile (src, dst) {
const content = await readFile(src) // await 等同于使用 .then
writeFile(dst, content)
}
async function writeFile(dst, content){
console.log(dst, content);
}
async function readFile(src){
console.log(src);
return 'readFile content'
}
async function main () {
try {
await copyFile('src', 'dst')
console.log('finished')
} catch (err) {
console.error(err)
}
}
console.log(1);
main();
console.log2;
结果: 1 src 2 (src readFile content) finishd
// 解析 main 函数 内的 copyFile 会 先解析成 一个 Promise 的 同步代码 然后拼接成 .then 的 异步代码 所以会有 1 后 先输出 src 再输出 2 Promise 代码 在上面
拓展
callback 转 promise
eg:
function ajax(url, callback){ //... } // callback
function ajaxPromise(url){ // promise
return new Promise((resolve, reject)=>{
ajax(url, (err, content)=>{
if(err){ reject(err); return }
resolve(content)
})
})
}
ajaxPromise('xxx.com').then((content)=>{
// 调用成功 处理
}).catch((err)=>{
// 调用失败 处理
})
promise 转 async
sync function main(){
try{
const content = await ajaxPromise('xxx.com');
}catch(err){
console.log(err);
}
}
callback 转 async
4. 现代 javascript class 专题 和 异步专题的更多相关文章
- 掌握 Ajax,第 2 部分: 使用 JavaScript 和 Ajax 发出异步请求
转http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro2/ 掌握 Ajax,第 2 部分: 使用 JavaScript 和 Ajax 发出异步请求 ...
- [js]javascript中4种异步
javascript中4种异步: 1.ajax 2.定时器 3.事件绑定 4,回调 定时器 //顺序执行 /* var s = 0; for (var i = 0; i < 10000; i++ ...
- c#封装DBHelper类 c# 图片加水印 (摘)C#生成随机数的三种方法 使用LINQ、Lambda 表达式 、委托快速比较两个集合,找出需要新增、修改、删除的对象 c# 制作正方形图片 JavaScript 事件循环及异步原理(完全指北)
c#封装DBHelper类 public enum EffentNextType { /// <summary> /// 对其他语句无任何影响 /// </summary> ...
- JavaScript 文件延迟和异步加载
JavaScript 文件延迟和异步加载 -般情况下,在文档的 <head> 标签中包含 JavaScript 脚本,或者导入的 JavaScript 文件. 这意味着必须等到全部 Jav ...
- Javascript的单线程和异步编程
运行时概念 下面的内容解释了一个理论上的模型.现代 JavaScript 引擎着重实现和优化了描述的几个语义. 可视化描述 栈 函数调用形成了一个栈帧. function foo(b) { var a ...
- 3. 现代 javascript 数组专题 和 对象专题
数组专题 展开运算符 使用...符号, 可以将数组"展开". 数组展开的妙用 ... eg: // 代替apply const foo = [1, 2, 3] const bar ...
- 2. 现代 javascript 新语法 及 对象专题
let , const 和 var javascript 里面的作用域 一个大括号 是一个作用域 { } var 会 在局部作用定义 被定义时 会提升作用域 如 if 的 {} 就属于 局部作用域 ...
- JavaScript 常用数组函数方法专题
1. 由字符串生成数组 split() 分割字符串,并将分割的部分作为一个元素保存在一个新建的数组中. var str1 = "this is an emample to using the ...
- JavaScript的同步与异步
1.手绘一张图说明. 2.为什么JavaScript是单线程(这里引用阮一峰老师的话) JavaScript的单线程,与它的用途有关. 作为浏览器脚本语言,JavaScript的主要用途是与用户互动, ...
随机推荐
- Sass - &引用父选择器
描述: 您可以使用&字符选择父级选择器. 它告诉父选择器应该插入的位置. 例一:&在前 h3 { font-size: 20px margin-bottom: 10px &.s ...
- Vulkan Device Memory
1.通过下面的接口,可以获得显卡支持的所有内存类型: MemoryType的类型如下: 2.引用索引3对内存的描述 我们可以通过调用vkGetPhysicalDeviceMemoryPropertie ...
- Springboot Bean循环依赖问题
参考博客原文地址: https://www.jb51.net/article/168398.htm https://www.cnblogs.com/mianteno/p/10692633.html h ...
- 【转】ASP.NET Core WebAPI JWT Bearer 认证失败返回自定义数据 Json
应用场景:当前我们给微信小程序提供服务接口,接口中使用了权限认证这一块,当我使用 JWT Bearer 进行接口权限认证的时候,返回的结果不是我们客户端想要的,其它我们想要给客户端返回统一的数据结构, ...
- VUE3.x 前瞻
文档: API Reference 教程 课件 1. 初始化项目 // ① npm i -g @vue/cli // ② vue create my-project // ③ npm install ...
- 面试题(9)之 leetcode-189
题目描述 解法一: /** * @param {number[]} nums * @param {number} k * @return {void} Do not return anything, ...
- K均值聚类算法
k均值聚类算法(k-means clustering algorithm)是一种迭代求解的聚类分析算法,其步骤是随机选取K个对象作为初始的聚类中心,然后计算每个对象与各个种子聚类中心之间的距离,把每个 ...
- Essay引用如何最大限度的降低抄袭率
今天要说到让无数人恨得要死.为了降重改的哭天喊地的“Paraphrase”.毕竟引用不是打两个引号复制粘贴就能凑字数完事的,无论国内外,都有查重率这个大敌在等着你.想要引用别人的论点论据,就少不了需要 ...
- 实验吧-隐写术-刷新 刷新 快刷新(f5-steganography)
题目:刷新 刷新 快刷新 其实这就算是很好的提示了,刷新的时候就是F5嘛,这个题就是F5隐写,用f5-steganography来解题. 题中的图片: f5-steganography下载链接:htt ...
- 【剑指Offer】面试题05.替换空格
题目 请实现一个函数,把字符串 s 中的每个空格替换成"%20". 示例 1: 输入:s = "We are happy." 输出:"We%20are ...