JS ES6

本文深入解析ES6新增的let、const、解构赋值、模板字符串、箭头函数、Promise、Iterator、Generator、Async/Await及Class等关键特性,通过实例演示如何提升JavaScript编程效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

变量 let

  • 块级作用域内有效
  • 不能重复声明
  • 不会预处理,不存在提升
var btns = document.getElementsByTagName('button');
for (let i = 0; i < btns.length; i++) {
    var btn = btns[i];
    btn.onclick = function(){
        alert(i)
    }
}
// for (var i = 0; i < btns.length; i++) {
//  var btn = btns[i];
//  (function(i){
//      btn.onclick = function(){
//          alert(i)
//      }
//  })(i)
// }

常量 const const key = 'Kevin'

解构赋值

//解构对象
let obj = {username: 'Tom', age: 20}
let {username, age} = obj;
console.log(username, age); //Tom 20

//解构数组
let arr = [20, 'ab', 'Tom']
let [,a,b] = arr;
console.log(a, b); //ab Tom

//多形参解构
function person({username, age}){
    console.log(username, age);
}
var p1 = {username: 'Kevin', age:28}
person(p1); //Kevin 28

模板字符串

let name = 'Kevin';
let str = `Hello Es6 String, I am ${name}.`;
console.log(str); //Hello Es6 String, I am Kevin.

对象简写

let username = 'Kevin';
let age = 28;
//省略同名属性
//省略方法function
let person = {
    username,
    age,
    getUserName() {
        return this.username;
    }
}
console.log(person); //{username: 'Kevin', age: 28, getUserName: f..}
console.log(person.getUserName()); //Kevin

箭头函数

//作用:定义匿名函数
let fun1 = () => console.log('fun1');
//一个形参时可省略括号;函数体无大括号时自动return结果
let fun2 = x => x*2;
//多个形参;函数体有大括号时不自动返回结果
let fun3 = (x, y) => x + y;
let fun4 = (x, y) => {
    console.log(x, y);
    return x + y;
}
//箭头函数没有自己的this,不是调用时候决定的,而是定义时候的所处对象
//技巧: 看this外层是否有函数
//1. 有:外层函数的this就是内部箭头函数的this
//2. 无:this指向window
let user = {
    name: 'Kevin',
    getUser: function(){
        console.log(this); //{name: "Kevin", getUser: ƒ}
    }
}
user.getUser(); //Kevin

let user2 = {
    name: 'Tom',
    getUser: () => {
        console.log(this);
    }
}
user2.getUser(); //window
三点运算符
//可变参数
function fun1(...values){
    console.log(arguments); //["a", "b", "c", callee: (...), Symbol(Symbol.iterator): ƒ]
    console.log(...arguments); //a b c
    console.log(values); //["a", "b", "c"]
    let args = Array.prototype.slice.call(arguments);
    console.log(args); //["a", "b", "c"]
}
fun1('a', 'b', 'c'); 

//扩展运算
let arr1 = [3,4,5];
let arr2 = [1,2,...arr1,6];
console.log(arr2); //[1, 2, 3, 4, 5, 6]
形参默认值
function Point(x = 0, y = 0){
    this.x = x;
    this.y = y;
}
let point = new Point();
console.log(point.x, point.y); // 0 0
Promise
let promise = new Promise((resolve, reject) => {        
    setTimeout(() => {
        resolve('yes');
        // reject('no');
    }, 1000)
})
promise
    .then((data) => {
        console.log(data); //yes
    }, (error) => {
        console.log(error); //no
    })

 //定义一个Get请求的方法
function sendGetAjax(url){
    //创建一个promise对象
    let promise = new Promise((resolve, reject) => {
        //初始化promise状态为pending
        //启动异步任务
        let request = new XMLHttpRequest();
        request.onreadystatechange = function () {
            if(request.readyState === 4){
                if(request.status === 200){
                    let data = request.response;
                    resolve(data);
                }else{
                    reject('error');
                }
            }
        };
        request.responseType = 'json';//设置返回的数据类型
        request.open("GET", url);//规定请求的方法,创建链接
        request.send();//发送
    })
    return promise;
}

Iterator

  • iterator是一种接口机制,为各种不同的数据结构提供统一的访问机制
//迭代器原理
function mockInterator(arr){
    var nextIndex = 0;
    return {
        next: function(){
            return (nextIndex < arr.length) ? {value: arr[nextIndex++], done: false} : {value: undefined, done:true}
        }
    }
}

let arr = [1,2,3,'abc'];
let obj = mockInterator(arr)
console.log(obj.next()); //{value: 1, done: false}
console.log(obj.next()); //{value: 2, done: false}
console.log(obj.next()); //{value: 3, done: false}
console.log(obj.next()); //{value: "abc", done: false}
console.log(obj.next()); //{value: undefined, done: true}
console.log(obj.next()); //{value: undefined, done: true}

// 原生具备iterator接口的数据(可用for of遍历)
//   1、Array
let arr3 = [1, 2, 'kobe', true];
for(let i of arr3){
  console.log(i);
}
//   2、arguments
//   3、set容器
//   4、map容器
//   5、String
let str = 'abcdefg';
for(let item of str){
  console.log(item);
}

Generator

  • ES6提供的解决异步编程的方案之一
function* sendXml() {
  // url为next传参进来的数据
  let url = yield getNews('http://localhost:3000/news?newsId=2');
  yield getNews(url);
}
function getNews(url) {
  $.get(url, function (data) {
    console.log(data);
    let commentsUrl = data.commentsUrl;
    let url = 'http://localhost:3000' + commentsUrl;
    // 当获取新闻内容成功,发送请求获取对应的评论内容
    // 调用next传参会作为上次暂停是yield的返回值
    sx.next(url);
  })
}


let sx = sendXml();
// 发送请求获取新闻内容
sx.next();

Async

async function sendXML(url) {
    return new Promise((resolve, reject) => {
        $.ajax({
            method: 'GET',
            url,
            success: data => resolve(data),
            error: error => reject(error)
        })
    })
}
async function getNews(url){
    let result = await sendXML(url);
    console.log('->', result);
    result = await sendXML(url + result.commentId);
    console.log('->', result);
}
getNews('http://localhost:30001/news?id=9');
Class
class Person {
    //调用类的构造方法
    constructor(name, age){
        this.name = name;
        this.age = age;

    }
    //定义一般的方法
    showName(){
        console.log(this.name, this.age);
    }
}
let person = new Person('kobe', 39);
console.log(person, person.showName());

//定义一个子类
class StrPerson extends Person{
    constructor(name, age, salary){
        super(name, age);//调用父类的构造方法
        this.salary = salary;
    }
    showName(){//在子类自身定义方法
        console.log(this.name, this.age, this.salary);
    }
}
let str = new StrPerson('weide', 38, 1000000000);
console.log(str);
str.showName();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值