ES2015+ 语法支持
JSVM2 支持部分 ES2015 (ES6) 及更高版本的现代 JavaScript 语法特性。
支持的 ES2015+ 特性
✅ 变量声明
let 和 const
// let - 块级作用域,可重新赋值
let count = 0;
count = 1; // 允许
if (true) {
let blockScoped = "只在块内可见";
console.log(blockScoped);
}
// console.log(blockScoped); // ReferenceError
// const - 块级作用域,不可重新赋值
const PI = 3.14159;
// PI = 3.14; // TypeError
const obj = { name: "张三" };
obj.name = "李四"; // 允许,只是对象内容改变
暂时性死区
console.log(x); // ReferenceError: 在声明前不能访问
let x = 5;
function example() {
// console.log(y); // ReferenceError
const y = 10;
return y;
}
✅ 箭头函数
基本语法
// 传统函数表达式
const add = function(a, b) {
return a + b;
};
// 箭头函数 - 简洁语法
const add = (a, b) => a + b;
// 单参数可省略括号
const double = x => x * 2;
// 无参数需要括号
const getRandom = () => Math.random();
// 多行函数体需要大括号和 return
const complex = (x, y) => {
const sum = x + y;
return sum * 2;
};
this 绑定特性
const obj = {
name: "对象",
// 传统方法 - this 指向调用对象
regularMethod: function() {
return this.name;
},
// 箭头函数 - this 继承外层作用域
arrowMethod: () => {
return this.name; // this 不是 obj
},
// 在方法中使用箭头函数
createHandler: function() {
return () => {
return this.name; // this 指向 obj
};
}
};
✅ 解构赋值
数组解构
const arr = [1, 2, 3, 4, 5];
// 基本解构
const [first, second] = arr;
console.log(first, second); // 1, 2
// 跳过元素
const [, , third] = arr;
console.log(third); // 3
// 剩余元素
const [head, ...tail] = arr;
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]
// 默认值
const [a, b, c, d, e, f = 0] = arr;
console.log(f); // 0
// 嵌套解构
const nested = [[1, 2], [3, 4]];
const [[a1, a2], [b1, b2]] = nested;