Skip to content

ES6 Features

Arrow Functions

Arrow functions มีไวยากรณ์ที่กระชับกว่าและ bind this โดยอัตโนมัติจากบริบทที่ประกาศ

js
// รูปแบบเดิม
function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => a + b;

Template Literals

ใช้ backticks (`) เพื่อสร้าง string ที่มีการแทรกตัวแปรหรือนิพจน์

js
const name = "John";
const greeting = `สวัสดี ${name}!`;

Destructuring Assignment

การแยกค่าจาก object หรือ array ให้กับตัวแปรหลายตัว

js
// Object destructuring
const person = { name: "John", age: 30 };
const { name, age } = person;

// Array destructuring
const colors = ["red", "green", "blue"];
const [first, second] = colors;

Default Parameters

กำหนดค่าเริ่มต้นให้กับพารามิเตอร์ของฟังก์ชัน

js
function greet(name = "Guest") {
  return `สวัสดี ${name}!`;
}

Spread Operator

ใช้ ... เพื่อกระจายสมาชิกของ iterable (เช่น array) หรือ properties ของ object

js
// กับ Array
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

// กับ Object
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

Classes

รูปแบบใหม่ในการสร้าง constructor functions และการสืบทอด

js
class Person {
  constructor(name) {
    this.name = name;
  }

  sayHello() {
    return `สวัสดี ฉันชื่อ ${this.name}`;
  }
}

class Employee extends Person {
  constructor(name, position) {
    super(name);
    this.position = position;
  }
}

Promises

Object ที่ใช้จัดการกับ asynchronous operations

js
const fetchData = () => {
  return new Promise((resolve, reject) => {
    // async operation
    if (success) {
      resolve(data);
    } else {
      reject(error);
    }
  });
};

fetchData()
  .then(data => console.log(data))
  .catch(error => console.error(error));

Let และ Const

ตัวแปรแบบใหม่ที่มี block scope

js
// let - สามารถเปลี่ยนค่าได้
let count = 1;
count = 2;

// const - ไม่สามารถ reassign ได้
const PI = 3.14;