es6基础学习(1)
1. 箭头函数
1.1 基本语法
// 传统写法letarr=[1,2,3,4,5];letresult1=arr.map(function(item){returnitem*2;});// 箭头函数写法letresult2=arr.map((item)=>item*2);console.log(result2);// [2, 4, 6, 8, 10]1.2 核心优势
✅ 优势1:简洁语法
| 场景 | 传统写法 | 箭头函数 |
|---|---|---|
| 单个参数 | function(x){ return x*2 } | x => x*2 |
| 多个参数 | function(x,y){ return x+y } | (x,y) => x+y |
| 无参数 | function(){ return 42 } | () => 42 |
// 各种写法示例letf1=()=>42;// 无参数letf2=x=>x*2;// 一个参数可省略括号letf3=(x,y)=>x+y;// 多个参数必须加括号letf4=(x,y)=>{// 多行代码需加花括号和 returnletsum=x+y;returnsum*2;};优势2:隐式返回
// 单行表达式自动返回(不需要 return)letdouble=x=>x*2;// 自动返回 x*2// 多行代码需要显式 returnletprocess=(x,y)=>{lettemp=x+y;returntemp*2;// 必须写 return};// 返回对象时需要加括号letgetUser=()=>({name:'张三',age:18});✅ 优势3:修复 this 指向问题
// ❌ 传统函数:this 指向调用者constobj={name:'对象',greet:function(){setTimeout(function(){console.log(this.name);// undefined(this 指向 window)},1000);}};// ✅ 箭头函数:this 指向定义时的对象constobj2={name:'对象',greet:function(){setTimeout(()=>{console.log(this.name);// '对象'(this 绑定到外层)},1000);}};1.3 不能使用箭头函数的场景
| 场景 | 原因 | 正确写法 |
|---|---|---|
| 构造函数 | 箭头函数没有自己的this | 使用普通函数 |
| 对象方法 | this 会指向全局 | 使用普通函数 |
| DOM 事件回调 | 需要动态 this 指向元素 | 使用普通函数 |
| 需要 arguments | 箭头函数没有 arguments | 使用普通函数或 rest 参数 |
2. 块级作用域
2.1 概念对比
| 作用域类型 | 说明 | 示例 |
|---|---|---|
| 全局作用域 | 全局变量 | var a = 1(全局) |
| 函数作用域 | 函数内有效 | function fn() { var b = 2 } |
| 块级作用域 | (ES6新增) {} | 内有效 let c = 3 |
2.2 实际应用
// ES5:只有函数作用域,没有块级作用域for(vari=0;i<5;i++){// ...}console.log(i);// 5(变量泄露)// ES6:块级作用域for(letj=0;j<5;j++){// ...}console.log(j);// ReferenceError: j is not defined// if 语句块if(true){letx=10;vary=20;}console.log(y);// 20(var 不受块级限制)console.log(x);// ReferenceError(let 受块级限制)3.类构建函数
3.1类的基本使用方法
es6新增类概念,可以使用class关键字声明一个类,之后以这个类来进行实例化。
类:抽象了对象的公共部分,它泛指某一大类
对象:特指某一个,通过类来实例化一个具体的对象
class Star { constructor(name,age) { this.name=name; this.age=age; } say (){ console.log(song) } } const star=new Star() star.say()注意:方法之间不能加逗号分割,同时方法不需要添加function关键字。
constructor构造函数
constructor方法是累的构造函数,用于传递参数,返回实例对象,通过new命令生成对象实例时,自动调用该方法,如果涅昭显示定义,类内部会自动给我们创建一个
创建实例
var ldh=new Star('李德华‘,18);
console.log(ldh.name)
3.2 类的构造方法
方法1导出实例(单例模式)
classUserController{asyncgetUsers(req,res){/* ... */}}module.exports=newUserController();// 导出类// app.js
constuserController=require('./controller.js');// 直接就是实例userController.getUsers(req,res);// 不需要 new方法2
classUserController{asyncgetUsers(req,res){/* ... */}}module.exports=UserController;// 导出类// app.js
constUserController=require('./user.controller');constuserController=newUserController();// 需要手动实例化userController.getUsers(req,res);3.3 类 工具类(静态方法)
user.js
classResponseHandler{// 静态方法staticsuccess(res,data){returnres.json({code:0,data});}staticerror(res,message){returnres.json({code:400,message});}}module.exports=ResponseHandler;app.js
constResponseHandler=require(./user.js)// 使用:直接通过类名调用ResponseHandler.success(res,{name:'张三'});ResponseHandler.error(res,'操作失败');📚总结
| 方式 | 导出 | 使用 | 适用场景 |
|---|---|---|---|
| 导出实例 | new Class() | 直接调用 | 单例、无状态 |
| 导出类 | Class | new Class() | 需要多实例、依赖注入 |
| 静态方法 | 不需要实例 | Class.method() | 工具函数 |
4 es6中新增字符串函数
4.1 startsWith()
检查是否以指定字符串开头,返回布尔值
varstr="321366199008092086"console.log(str.startsWith('32'));//true4.2 endsWith()
检查是否以指定字符串结尾,返回布尔值
varstr2="CSS-HTML-JAVASCRIPT";console.log(str2.endsWith("JAVASCRIPT"));//true4.3 includes()
检查字符串是否包含指定字符串 ,返回布尔值
varstr3='2jipmjhhklkl';console.log(str3.includes('l'));//true4.4 repeat()
指定字符串重复次数
varstr4="你好哇~";console.log(str4.repeat(4));//你好哇~你好哇~你好哇~你好哇~5. ES6模板字符串
1.如果使用模板字符串表示多行字符串,所有的空格和缩进都会被保留在输出之中。
可以包涵换行
$('#box').html(`<ul> <li>哈哈哈</li> <li>哼哼哈哈哈</li> <li>哦哦哦</li> </ul>`);2.可以嵌入变量
使用美元符号和大括号包裹变量${对象名.属性名}
letname='wcy',age=18,gender='male';console.log(`name :${name}, age :${age}, gender :${gender}`3.可以原生输出
lettest1=String.raw;letresult1=test1`哈哈哈哈我是谁\\`;console.log(result1);//哈哈哈哈我是谁\\4.模板字符串还可以嵌套
5.大括号内部可以放入任意的JavaScript表达式,可以进行运算,以及引用对象属性,而且还能调用函数
6.标签函数会接收多个参数。
第一个参数是包含了字符串字面量(即那些没有变量替换的值)的数组
后面的参数是已经替换后的变量值
functionyun_fun(str,one,two){console.log(str,one,two)}letone="wcy"lettwo="wt"yun_fun`${one}我是谁?我在哪里?${two}`