迈入大前端-第二章

本文详细介绍了ECMAScript从2015到2017的版本更新,包括ES6和ES5的区别、块级作用域、新特性如Promise、Set、Map、Symbol等。同时,探讨了TypeScript的强类型、静态类型、类和接口等概念,以及其在错误暴露、代码准确性和重构上的优势。最后,简要提及了JavaScript的性能优化,特别是垃圾回收算法。
摘要由CSDN通过智能技术生成

在这里插入图片描述


前言

梦想就是一种让你感到坚持就是幸福的东西

一、ECMAScript概述

  • ECMAScript(ES)其实也是一种脚本语言,只提供了最基本的语法,例如如何定义变量和函数,循环语句,只停留在语言层面,不能完成实际应用中的功能开发
  • JavaScript(JS)是ES的一门扩展语言JS的语言本身是ES
  • JS在web环境中在这里插入图片描述
  • JS在node环境中
    在这里插入图片描述
  • 2015开始保持每年一个大版本的迭代,也是从2015开始以年份来命名新版本,也有用ES6泛指所有新标准(ES2015是大改的一版
    在这里插入图片描述

二、ES2015

1.ES6和ES5的变化

  • 解决原有语法上的一些问题或者不足(let,const提供的块级作用域
  • 对原有语法进行增强(解构[a,b,c]=[1,2,3],展开…,参数默认值(status=200),模板字符串``
  • 全新的对象,全新的方法,全新的功能(Promise对象,Object.assign()方法,Proxy
  • 全新的数据类型和数据结构(Symbol,Set,Map

2.作用域

  • 原有:全局作用域,函数作用域,新增:块级作用域(let和const
  • 块级作用域代码示例
//if的花括号
if(true){
}
//for的花括号  循环体中有2层作用域 内层 for循环的,和外层花括号的
for(var i =0;i<3;i++){
}
  • let和const不会提升,先声明后调用
  • let 声明变量可变,const声明对象和函数可以改变其内部的值,其他类型是不可变,不能重新指向新的内存地址,且声明时必须赋值
  • 在同一个作用域下,let const不能同名
  • let const只有块级作用域概念
  • 建议先用const再用let最后var

3.ES2015新特性

  • 数组的结构 示例
//数组的结构
const arr=[1,2,3]

let [a,b,c]=arr  //a=1 b=2 c=3

let [,,c]=arr //c=3

let [a,...b]=arr  //b=[2,3]

let [a,b,c,d]=arr //d=undefined

let [a,b,c=123,d="321"]=arr //c=3,d="321"
  • 对象的结构 示例
//对象的结构 
const obj ={name:"lcy",age:18}
let {name} =obj // name="lcy"
//起变量名
let {name:nameOther}=obj //nameOther="lcy"
//取默认值
let {name:nameOther="lcy----"}=obj 
//抽出公共方法
let {log} =console
log("321")
  • 模板字符串 示例
//模板字符串
const say='人心是暖的'
const str=`天是蓝的,水是甜的${say},${1+2,${Math.random()}}`

//带标签的模板字符串
const name='lcy'
const sex ='man'
function fn(string,name,sex){
	//string =['hi,','is a ','.'] name='lcy' sex='man'
}
const result =fn`hi,${name} is a ${sex}.`
  • 字符串String的扩展方法includes()是否存在,startsWith()是否开头,endsWith()是否结尾
  • 参数默认值 fn(value=321)
  • 剩余参数fn(…args)
  • 展开数组 console.log(…arr)
  • 箭头函数 ()=>{} 箭头函数没有this指向,会捕获上下文的this
  • 对象拷贝方法 Object.assign({},obj) 浅拷贝 同一个内存地址
  • Object.is(NaN,NaN) // true NaN===NaN //false 一般不用
  • Proxy类型 比defineProperty更合理
    • Proxy不需要侵入对象,defineProperty需要单独定义对象的属性
    • Proxy更好监视数组
    • defineProperty只能监听属性的读写,Proxy可以监听更多比如对象中方法调用,删除操作
    • Proxy 示例
const personProxy=new Proxy(person)
get(target,property){},
set(target,property,value){}
  • Reflect统一的对象操作API 静态类 Reflect.get()目前13个API
  • Promise对象,异步回调解决方案,异步编程重点
  • Class类 static静态方法 Extends继承 示例
class Person{
    constructor(name,age){
        this.name=name
        this.age=age
    }
    say(){
        console.log(this.name)
    }
    //静态方法
    static run(){}
}
const p= new Person('lcy',18)
Person.run()
p.say()  //'lcy'

class Student extends Person{
    constructor(name,age,number){
        super(name,age)
        this.number=number
    }
    hello(){
    super.say()
    }
}
  • Set数据结构 类数组 数据不重复
  • Map数据结构 任意类型作为键,对象只能以字符串(非字符串转成字符串)
  • Symbol类型值是一个独一无二的值,可以为对象添加一个独一无二的属性名,防止对象属性名重名产生的问题,因为属性名独一无二外界也访问不到,可以很好的实现私有成员
  • for of 循环
  • Iterable接口 可迭代的 .next()返回 {value:’’,done:true} generator生成器中也有 (比较麻烦!!!)
  • 生成器函数 Generator function * fn(){} 星号就是标明生成器函数
  • ES Modules 模块化标准

三、ES2016

  • 数组Includes方法
  • 指数运算符 **

四、ES2017

  • Object.values 返回对象所有的值
  • Object.entries 数组返回对象所有的键值对
  • Object.getOwnPropertyDescriptors 配合对象get set属性使用
  • String.padStart(3,‘0’)和String.padEnd(16,’-’)

五、TypeScript

1.类型

  • 强类型与弱类型(类型安全)
  • 强类型语言层面限制函数的实参类型必须与形参类型相同
  • 弱类型语言层面不会限制实参的类型
  • 静态类型与动态类型(类型检查)

2.静态类型:

一个变量声明时它的类型就是明确的,之后不可更改

3.动态类型:

运行阶段才能明确变量类型,变量的类型随时可以改变

JavaScript 是弱类型且动态类型

4.强类型的优势

  • 错误更早暴露
  • 代码更智能,编码更准确
  • 重构更牢靠
  • 减少不必要的类型判断

tsconfig.json示例

{
    "compilerOptions": {
        /* Visit https://aka.ms/tsconfig.json to read more about this file */
        /* Basic Options */
        // "incremental": true,                   /* Enable incremental compilation */
        "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
        "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
        "lib": [ "ES2015","DOM" ],                             /* Specify library files to be included in the compilation. */
        // "allowJs": true,                       /* Allow javascript files to be compiled. */
        // "checkJs": true,                       /* Report errors in .js files. */
        // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
        // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
        // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
        "sourceMap": true,                     /* Generates corresponding '.map' file. */
        // "outFile": "./",                       /* Concatenate and emit output to single file. */
        "outDir": "TypeScript/dist", /* Redirect output structure to the directory. */
        "rootDir": "TypeScript/src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
        // "composite": true,                     /* Enable project compilation */
        // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
        // "removeComments": true,                /* Do not emit comments to output. */
        // "noEmit": true,                        /* Do not emit outputs. */
        // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
        // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
        // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
        /* Strict Type-Checking Options */
        "strict": true, /* Enable all strict type-checking options. */
        // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
        // "strictNullChecks": true,              /* Enable strict null checks. */
        // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
        // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
        // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
        // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
        // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */
        /* Additional Checks */
        // "noUnusedLocals": true,                /* Report errors on unused locals. */
        // "noUnusedParameters": true,            /* Report errors on unused parameters. */
        // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
        // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
        /* Module Resolution Options */
        // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
        // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
        // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
        // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
        // "typeRoots": [],                       /* List of folders to include type definitions from. */
        // "types": [],                           /* Type declaration files to be included in compilation. */
        // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
        "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
        // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
        // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */
        /* Source Map Options */
        // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
        // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
        // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
        // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
        /* Experimental Options */
        // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
        // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
        /* Advanced Options */
        "skipLibCheck": true, /* Skip type checking of declaration files. */
        "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
    }
}

5.原始数据类型

  • string number boolean void null undefined Symbol //要配置ES6

6.标准库

  • 需要哪个就引入哪个,以下方式二选一
  • 标准库就是内置对象所对应的声明
"target": "es5", // 对应的声明文件,这里只会引用es5标准库
"lib": ["ES2015","DOM"],  // 只写一个会覆盖所有的标准库,所以需要依次把需要的添加进来

7.作用域问题

  • 不同文件中相同变量名称的情况,会报出重复定义变量的错误
// const a = 'bbb'
// 解决办法1,立即执行函数
(function () {
    const a = 'bbb'
})()
// 解决办法2
const a = 'ccc'
// 作为一个模块导出,模块是有单独模块作用域的,将模块内的成员变成模块作用域中的局部成员
export { }

8.Object 类型

  • Object类型泛指 对象,数组,函数

9.数组类型

const arr1: Array<number> = [1, 2, 3]
const arr2: number[] = [1, 2, 3]

10.元祖(tuple)

  • 必须类型相同,长度相同
const tuple: [number, string] = [18, 'jack']

11.枚举(enum)

enum post {
    title = 'Hello TypeScript',
    num = 0
}
// 纯数字类型的枚举可以不用赋值,只需要写名称即可,值默认是+1的
enum num {
    one,
    two
}

// 数字枚举会在编译后变成一个双向的键值对对象
console.log(post[0]); // num 
console.log(num.one); // 0
console.log(num[0]); // one

const enum num1 {
    one,
    two
}
// 如果不需要用索引访问枚举成员,则可以使用常量枚举
// 索引无法访问到常量枚举
// console.log(num1[0]); // 会在编译时就报错

12.类(Class)

  • 访问修饰符 public private protected
class Person {
    // 默认就是公有属性
    public name: string
    // 属性“age”为私有属性,只能在类“Person”及其子类中访问。
    private age: number
    // 属性“sex”受保护,只能在类“Person”及其子类中访问。
    protected sex: string
    constructor(name: string, age: number) {
        this.name = name
        this.age = age
        this.sex = 'man'
    }
    say(value: string): void {
        console.log(`my name is ${this.name},${value}`)
    }
}

const jack = new Person('jack', 18)
// 外部只能访问到name属性 say方法
console.log(jack.name) // jack
jack.say('hello world') // my name is jack,hello,world

13.接口(Interface)

  • implements实现接口
  • 类要实现接口必须要有接口中的成员
  • 约束类之间公共的能力

14.抽象类(abstract)

  • 抽象类不同于接口,抽象类可以包含具体的实现,而接口只能是成员抽象不能实现
  • 定义为抽象类之后只能被继承,不能使用new实例化

15.泛型

  • 在定义函数,接口,类的时候没有指定具体类型,在使用的时候才指定具体类型
  • 如果指定具体的值,value参数想要改变类型就需要再定义一次函数很麻烦
  • 把类型变成一个参数,把不明确的类型用T去代表
  • 在函数名后面使用

六.性能优化

1.常见GC算法

  • 引用计数

    核心思想

    • 设置引用数,判断当前引用数是否为0
    • 引用计数器
    • 引用关系改变时修改引用数字
    • 引用数字为0时立即回收

    优点

    • 发现垃圾时立即回收
    • 最大限度减少程序暂停

    缺点

    • 无法回收循环引用的对象
    • 时间开销大
  • 标记清除

    • 核心思想: 分标记和清除二个阶段完成
    • 遍历所有对象找标记活动对象
    • 遍历所有对象清除没有标记的对象
    • 回收相应的空间

    优点

    • 可以回收循环引用的对象

    缺点

    • 地址不连续,空间碎片化,浪费空间
    • 不会立即回收垃圾对象
  • 标记整理

    • 标记整理可以看作是标记清除的增强
    • 标记阶段的操作和标记清除一致
    • 清除阶段会先执行整理,移动对象位置,在地址上连续再清除

    优点

    • 减少碎片化空间

    缺点

    • 不会立即回收垃圾对象
  • 分代回收

    V8

  • V8是一款主流的JavaScript执行引擎

  • V8采用即使编译

  • V8内存有限制,64位系统是1.5G, 32位系统是800MB(对于web应用来说这个内存大小时足够使用的,内部垃圾回收机制决定)

    V8垃圾回收策略

    • 采用分代回收思想
    • 内存分为新生代、老生代

    v8新生代

    • 小空间用域存储新生代对象(32MB | 16MB) 内存一样有限制

    • 新生代指的就是存活时间较短的对象(局部作用域中的)
      回收过程说明

      • 回收过程采用复制算法 + 标记整理
      • 新生代内存区分为二个等大小的空间
      • 使用中的空间为From, 空闲的空间为To
      • 活动对象存储于From空间
      • 标记整理后将活动对象拷贝至To
      • From与To交换空间完成释放

      回收细节说明

      • 拷贝过程中可能出现晋升
      • 晋升就是将新生代对象移动至老生代
      • 一轮GC还存活的新生代需要晋升
      • To空间使用率超过25%也会晋升

    v8老生代

    • 老生代对象存放在右侧老生代区域

    • 内存限制(1.4G | 700MB)

    • 老生代对象指存活时间较长的对象(全局变量,闭包)
      回收过程说明

      • 回收过程主要采用标记清除、标记整理、增量标记算法
      • 首先使用标记清除完成垃圾空间的回收
      • 如果新生代对象晋升时老生代对象内部内存不足,则会采用标记整理进行空间优化
      • 采用增量标记对回收效率进行优化
      • 增量标记工作原理: 对象存在直接可达和间接可达,将遍历对象标记,拆分成多个小步骤,先标记直接可达对象。间接可达的标记与程序执行交替执行,最终完成清除。

      回收细节说明

      • 新生代区域垃圾回收使用空间换时间
      • 老生代区域垃圾回收不适合复制算法

总结

以上就是ES 新特性与 TypeScript、JS 性能优化学习的总结,性能优化有时间再补充,狗命重要!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值