JavaScript ES6 特性

AdrainHuang發表於2020-12-19

JavaScript ES6 特性

下面的程式碼主要是描述以下內容:

  1. let是塊區作用域,不會變數提升.var也是塊做作用域,但是會變數提升。
  2. …展開操作符作用於陣列。
  3. 陣列解構賦值。
  4. 物件增強。
  5. …展開操作符作用於物件。
  6. 物件解構賦值。
  7. for/of 結合迭代。
  8. 類繼承。
  9. get/set使用。
  10. 字串複製(repeat)。
  11. 函式預設值設定。
  12. 箭頭函式(arrow function) =>,會保持上下文 this。
  13. 生成器 generator(function*), yield關鍵字(暫停執行函式,返回yield 後面的表示式)。
  14. promise 延時操作。
  15. fetch demo。
  16. aysnc/await。
//1.let是塊區作用域,不會變數提升.var也是塊做作用域,但是會變數提升。
{
    let a = 12;
    var b = 52;
}
// console.log(a)// Uncaught ReferenceError: a is not defined
console.log(b)// 52

//2. 陣列展開操作符(...) array spread operator
let cats = ["Biscuit", "Jungle"];
let dogs = ["Stella", "Camper"];

let animals = ["Smoky", "Miro", "Swimmy", ...cats, ...dogs];
//["Smoky", "Miro", "Swimmy", "Biscuit", "Jungle", "Stella", "Camper"]
console.log(animals)

//3.陣列解構賦值 destructing arrays
let [first, fifth] = ["Smoky", "Miro", "Swimmy", "Camper", "Jungle"];
console.log(first);//Smoky
console.log(fifth);//Miro

let [one, , , , five] = ["Smoky", "Miro", "Swimmy", "Camper", "Jungle"];
console.log(one);//Smoky
console.log(five);//Jungle
// 4. 物件增強
// ES5
function skierES5(name, sound) {
    return {
        name: name,
        sound: sound,
        powderYell: function () {
            let yell = this.sound.toUpperCase();
            console.log(`${yell}! ${yell}!`)
        }
    }
}

skierES5("Sendy", "yeah").powderYell();//YEAH! YEAH!

// ES6
function skierES6(name, sound) {
    return {
        name,
        sound,
        powderYell() {
            let yell = this.sound.toUpperCase();
            console.log(`${yell}! ${yell}!`)
        }
    }
}
skierES6("Sendy", "yeah").powderYell();//YEAH! YEAH!

//5. 展開操作符(...)作用於物件
const daytime = {
    breakfast: "oatmeal",
    lunch: "peanut butter and jelly"
};

const nighttime = "mac and cheese"

const backpackingMeals = {
    ...daytime,
    nighttime
}

//{breakfast: "oatmeal", lunch: "peanut butter and jelly", nighttime: "mac and cheese"}
console.log(backpackingMeals);

// 6.物件解構賦值
const { title, price } = {
    title: "Rebuen",
    price: 7,
    description: "A classic",
    ingredients: ["bread", "corned beef", "dressing", "sauerkraut", "cheese"]
}

console.log(title, price)//Rebuen 7

const vacation = {
    destination: "Chile",
    travelers: 2,
    activity: "skiing",
    cost: "so much"
}
function marketing({ destination, activity }) {
    return `Come to ${destination} and do some ${activity}`;
}

console.log(marketing(vacation))//Come to Chile and do some skiing

//7.for/of 結合迭代
for (let letter of "javascript") {
    console.log(letter)
    // j
    // a
    // v
    // a
    // s
    // c
    // r
    // i
    // p
    // t
}

let topics = new Map();
topics.set("HTML", "/topic/html");
topics.set("CSS", "/topic/css");
topics.set("Javascript", "/topic/javascript");

for (let topic of topics) {
    // ["HTML", "/topic/html"]
    // ["CSS", "/topic/css"]
    // ["Javascript", "/topic/javascript"]
    console.log(topic)
}

//8. 類繼承
class Vehicle {
    constructor(description, wheels) {
        this.description = description;
        this.wheels = wheels;
    }
    describeYourself() {
        console.log(`I am a ${this.description} with ${this.wheels}`);
    }
}

class SemiTruck extends Vehicle {
    constructor() {
        super("semi truck", 18);
    }
}
let groceryStoreSemi = new SemiTruck();
groceryStoreSemi.describeYourself();//I am a semi truck with 18

//9. get set使用 個人感覺很變扭,沒必要這樣做
class Hike {
    constructor(distance, pace) {
        this.distance = distance;
        this.pace = pace;
    }

    get lengthInHours() {
        return `${this.calcLength()} hours`;
    }

    calcLength() {
        return this.distance / this.pace;
    }
}

const mtTallac = new Hike(10, 2);
console.log(mtTallac.lengthInHours)//5 hours

//10. string.repeat
console.log("Hi".repeat(3));//HiHiHi

//11. 函式設定預設值
function add(x = 5, y = 6) {
    console.log(x + y);
}
console.log(add())//11

//12. 箭頭函式arrow function
// ES5
// let studentList = function(students){
//     console.log(students);
// }

// ES6
let studentList = (students) => {
    console.log(students);
}

studentList(["A", "B", "C"])//["A","B","C"]

//ES5
let person = {
    first: "Angie",
    hobbies: ["bike", "hike", "ski"],
    printHobbies: function () {
        _this = this;
        this.hobbies.forEach(function (hobby) {
            let string = `${_this.first} likes to ${hobby}`;
            console.log(string);
        });
    }
};


// Angie likes to bike
// Angie likes to hike
// Angie likes to ski
person.printHobbies();

//ES6 arrow function
let personES6 = {
    first: "Angie",
    hobbies: ["bike", "hike", "ski"],
    printHobbies: function () {
        this.hobbies.forEach((hobby) => {
            let string = `${this.first} likes to ${hobby}`;
            console.log(string);
        });
    }
}
// Angie likes to bike
// Angie likes to hike
// Angie likes to ski
personES6.printHobbies();

// 13. 生成器 generator(function*), yield關鍵字(暫停執行函式,返回yield 後面的表示式)。
function* director() {
    yield "Three";
    yield "Two";
    yield "One";
    yield "Action";
}

let countdown = director();
console.log(countdown.next().value);
console.log(countdown.next().value);
console.log(countdown.next().value);
console.log(countdown.next().value);

//14.promise 延時操作
const delay = (seconds) =>
    new Promise((resolves, reject) => {
        if (typeof seconds !== "number") {
            reject(new Error("seconds must be a number"));
        }
        setTimeout(resolves, seconds * 1000)
    });
delay(2).then(() => console.log("2 sec"));//2 sec
delay("one").then(() => console.log("1 sec"));//seconds must be a number

//15. fetch demo
let getSpacePeople = () =>
    fetch("http://api.open-notify.org/astros.json")
        .then(res => res.json())

let spaceNames = () =>
    getSpacePeople()
        .then(json => json.people)
        .then(people => people.map(p => p.name))
        .then(names => names.join(","));
//Sergey Ryzhikov,Kate Rubins,Sergey Kud-Sverchkov,Mike Hopkins,Victor Glover,Shannon Walker,Soichi Noguchi
spaceNames().then(console.log);

//16. async await
const gtihubReuqest = async (login) => {
    let response = await fetch(`https://api.github.com/users/${login}`);
    let json = await response.json();
    let summary = `${json.name}, ${json.company}`;
    console.log(summary)
};

gtihubReuqest("Tony");//Tony Narlock, @peergradeio

相關文章