ES6 一些特性
# 解構
Expression 表達式
Statement 陳述式
Expression => 可以用 ()包起來的
Statement => 無法用()包起來的
ex:
if (1>2)
字串模板也支援多行字串
arrow function 內的 this 會等同於外部的this
const nums = [1,2,3];
const first = nums[0];
const second = nums[1];
可以改用
const [first, second] = nums;
# 要只取第二個
const [, second] = nums;
# 預設值
# 原本 fourth 應該是 undefined, 但透過後面的 assign 給定預設值
const [, second, third, fourth = 0] = nums;
# 值交換
let a = 1;
let b = 2;
[a, b] = [b, a];
# 剩餘部分
const nums = [1,2,3,4];
const [first, ...other] = nums;
# nums => [2,3,4]
# 物件解構
const points = {x:1,y:2};
# x = 1
const {x} = points;
# rename x to px (只限定物件, 不可以用在Array)
const {x:px} = points;
Expression 表達式
Statement 陳述式
Expression => 可以用 ()包起來的
Statement => 無法用()包起來的
ex:
if (1>2)
表達式
1+2;
const a;
a+2;
字串模板
字串模板內可以放入表達式
function greet(name, days) {
console.log(`Hello, ${name}! It has been ${days * 24} hours not seen you!`);
}
# or
function greet(name, days) {
console.log(`Hello, ${name}! ${(days < 7) ? '' : 'Long time no see'}`);
}
字串模板也支援多行字串
const str = `
123456
12345
1234567
`;
arrow function 內的 this 會等同於外部的this
const a = () => {
// 此處的this等同於外面 console.log(this)的this
const aa = () => {
// 此處的this也等同於外面 console.log(this)的this
}
}
console.log(this)
留言
張貼留言