您的位置:首页 > 文旅 > 美景 > ES6常用功能/新特性

ES6常用功能/新特性

2024/10/5 21:19:30 来源:https://blog.csdn.net/huyijian1314/article/details/140441473  浏览:    关键词:ES6常用功能/新特性
  • 模块化

两个关键字:export、import

// util.js
export function getData (str) {// do something
}
// index.js
import {.getData } from './util';getData(args) // do something

es6模块化,在浏览器中需要通过webpack/rollup打包。这里我们也可以比较下两者打包结果的区别。查看打包后的代码,webpack有很多自己缝状的辅助函数,而rollup除了定义的amd/umd标准函数外,其他都是自己的逻辑代码。

  • class

以下例子可以看出es6中class的本质就是js构造函数的语法糖。但是使用class写法,语意更加清晰、简洁

// class.js
// class 方式
export class Animals {constructor(name) {this.name = name;}eat() {console.log(`${this.name} is eating`);}
}export class Dog extends Animals {constructor(name) {super(name);this.name = name;}bark() {console.log(`${this.name} is barking`);}
}// 使用function方式
export function Animal(name) {this.name = name;this.eat = function() {console.log(`function: ${this.name} is eating`);}
}
export function Dog2(name) {// Animal.call(this, name);this.bark = function() {console.log(`function: ${this.name} is barking`);}
}
Dog2.prototype = new Animal('dog2');

// index.js
import { Dog, Dog2 } from './class.js'const dog = new Dog('旺财')
dog.bark()
dog.eat()const dog2 = new Dog2('小强')
dog2.bark()
dog2.eat()
  • promise

promise用来解决js中的callback hell。它有3种状态:pending、fullfilled、rejected

const getData = new Promise((resolve, reject) => {// do something successif(true) {resolve();} else {reject();}
})
// 使用
getData.then(res => {// 成功处理
}).catch(err => {// 失败处理
})
  • let/const
let a = 10;
const b = 10;
a = 20; // 正确
b = 20; //报错
  • 多行字符串/模板变量
const name = 'zhangsan';
const age = 20;
const str = `
<div><p>${name}</p><p>${age}</p>
</div>
`
  • 解构赋值
const obj = {a: 'xxx',b: 'ccc'
}
const {.a: names } = obj;
  • 块级作用域
// JS
var obj = {.a: 100, b: 200 };
for(var item in obj) {console.log(item);
}
console.log(item);
// ES6
const obj = {.a: 100, b: 200 };
for(let item in obj) {console.log(item);
}
console.log(item);
  • 函数默认参数
function getData (a, b = 10) {console.log(a, b);
}
  • 箭头函数

箭头函数可以改变js函数烦人的this指向window问题,将this指向最近一层

function fn () {const arr = [1, 2, 3, 4, 5, 6];arr.map(function(item) {console.log('js:', this);return item + 1;});arr.map((item, index) => {console.log('es6:', this);return item + 1;})
}fn.call({ a: 100 })
// 可以思考一下打印结果

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com